是否有必要为新的字符串对象进行实例化,如以下代码所示:
NSString *newText = [[NSString alloc] initWithFormat:@"%@",sender.titleLabel.text];
或者我们可以简单地运行以下代码:
NSString *newText = sender.titleLabel.text;
我相信这会返回相同的结果。那么我们什么时候知道是否需要“alloc”和“init”,什么时候不需要呢?
谢谢
甄
是否有必要为新的字符串对象进行实例化,如以下代码所示:
NSString *newText = [[NSString alloc] initWithFormat:@"%@",sender.titleLabel.text];
或者我们可以简单地运行以下代码:
NSString *newText = sender.titleLabel.text;
我相信这会返回相同的结果。那么我们什么时候知道是否需要“alloc”和“init”,什么时候不需要呢?
谢谢
甄
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.
当您使用:
NSString *newText = sender.titleLabel.text;
您只是在 sender.titleLabel.text 处设置一个指向现有对象的指针。你告诉编译器这个新指针指向一个 NSString 类型的对象。
注意: 指针 newText 和 sender.titleLabel.txt 现在都指向同一个对象,因此对基础对象所做的更改(例如更改文本)将在您使用任一指针访问对象时反映出来。
注2:当您使用时:
NSString *newText = [[NSString alloc] initWithFormat:@"%@",sender.titleLabel.text];
您创建了一个全新的对象(通过使用 alloc),然后在执行 alloc 操作时使用sender.titleLabel.text的字符串值初始化这个新对象。现在newText和sender.titleLabel.text是两个完全不同的 NSString 对象,它们彼此之间没有任何关系,并且可以完全独立地进行更改/管理/使用/dealloc'd。