可可串问题 [英] Cocoa String Question

查看:101
本文介绍了可可串问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSString,我想将其值写入NSMutableString.这是有效的吗?

I have a NSString and I want to write its value to a NSMutableString. Is this valid:

NSString *temp = [NSString stringWithString:@"test"];
NSMutableString *mutable = temp;

我问,因为尽管这似乎可行,但我认为这会将temp和mutable分配给相同的地址空间.将值传递给方法或从方法返回值时,我经常遇到这个问题.有时我看到其他人这样做或使用stringWithString或initWithString创建可变的字符串.谢谢

I ask because although this seems doable, I would think that this would assign both temp and mutable to the same address space. I have this question a lot when passing values into a method or returning values from a method. Sometimes I see other people do this or create the mutable string with stringWithString or initWithString. Thanks

推荐答案

您可以使用mutableCopy方法,该方法创建接收者的可变副本,并应用于采用

You can use the mutableCopy method, which creates a mutable copy of the receiver and applies to any class which adopts the NSMutableCopying protocol (of which NSString is one of them):

NSString *temp = [NSString stringWithString:@"test"];
NSMutableString *mutable = [temp mutableCopy];

这将创建字符串的可变副本,作为新的字符串实例.在这种情况下,它不适用,因为temp是自动发布的字符串,但是如果您不再需要它,则需要释放已复制的旧字符串.

This will create a mutable copy of the string, as a new string instance. In this case it doesn't apply, as temp is an autoreleased string, but you would otherwise need to release the old string that you have made a copy of, if you no longer need it.

由于mutableCopy包含副本",所以您需要对新字符串进行内存管理(根据Apple

Since mutableCopy contains "copy", then you need to memory-manage the new string (you take ownership of it according to the Apple Object Ownership Policy).

您使用的方法只是将mutable分配为指向先前实例化的NSString的指针.

The method that you have used simply assigns mutable as a pointer to the previously instantiated NSString.

这篇关于可可串问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆