声明一个新的String对象时,是否需要先实例化它?
是否有必要像下面的代码所示那样实例化一个新的字符串对象:
NSString *newText = [[NSString alloc] initWithFormat:@"%@",sender.titleLabel.text];
或者我们可以简单地运行以下代码:
NSString *newText = sender.titleLabel.text;
我相信它会返回相同的结果。那么我们什么时候知道“alloc”和“init”是否需要,什么时候不需要?
谢谢
甄
Is it necessary to do instantiation for a new string object as the following code shows:
NSString *newText = [[NSString alloc] initWithFormat:@"%@",sender.titleLabel.text];
Or can we simply run the following code:
NSString *newText = sender.titleLabel.text;
which I believe will return the same result. So when do we know if "alloc" and "init" is required and when they are not?
Thanks
Zhen
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您使用:
您只是设置一个指向 sender.titleLabel.text 处现有对象的指针。您告诉编译器这个新指针指向 NSString 类型的对象。
注意:指针 newText 和 sender.titleLabel.txt 现在都指向同一个对象,因此当您使用任一指针访问对象时,将反映对基础对象所做的更改(例如更改文本) 。
注释 2: 当您使用时:
您创建了一个全新的对象(通过使用 alloc),然后使用字符串值 sender.titleLabel.text 初始化了这个新对象> 执行分配操作时。现在 newText 和 sender.titleLabel.text 是两个完全不同的 NSString 对象,它们彼此不相关,并且可以完全更改/管理/使用/释放彼此独立。
When you use:
you are just setting a pointer to the existing object at sender.titleLabel.text. You are telling the compiler that this new pointer points to an object of type NSString.
Note: the pointers newText and sender.titleLabel.txt now both point to the same object so changes made to the underlying object (such as changing the text) will be reflect when you access the object using either pointers.
Note 2: when you used:
You created an entirely new object (by using alloc) and then you init'd this new object with the string value of sender.titleLabel.text at the time the alloc operation was executed. Now newText and sender.titleLabel.text are two totally different NSString objects that are not related in anyway to each other and can be changed/managed/used/dealloc'd completely independently of each other.
您可以简单地使用分配(
newText = sender.titleLabel.text;
)。顺便说一句,您的两个示例的结果并不相同:在第一个示例中您创建了一个新对象,在第二个示例中您重用了现有对象。在第一个示例中,您需要稍后调用
[newText release];
(或 autorelease),在第二个示例中则可能不需要。如果您打算将字符串存储在实例变量中,则应复制它 (
myInstanceVariable = [sender.titleLabel.text copy];
)。原因是因为它可能是 NSMutableString 的一个实例,它可能会发生变化,从而产生意外的行为。You can simply use the assignment (
newText = sender.titleLabel.text;
).The results of your two examples are not the same, BTW: in your first example you create a new object, in the second one you reuse an existing one. In the first example, you need to later on call
[newText release];
(or autorelease), in your second example you may not.If you intend to store the string in an instance variable you should copy it (
myInstanceVariable = [sender.titleLabel.text copy];
). The reason is because it might be an instance of NSMutableString which can change and thus yield unexpected behavior.