Search code examples
objective-cinitalloc

When declaring a new String Object, is it necessary to instantiate it first?


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


Solution

  • 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.