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 follo开发者_Python百科wing 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
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.
When you use:
NSString *newText = sender.titleLabel.text;
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:
NSString *newText = [[NSString alloc] initWithFormat:@"%@",sender.titleLabel.text];
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.
精彩评论