What is the difference between:
NSString *string1 = @"This is string 1.";
and
NSString *string2 = [[NSString alloc]initWithString:@"This is string 2.];
Why am I not allocating and initializing the first string, yet it still works? I thought I was supposed to allocate NSString since it is an object?
In Cocoa Touch,
-(IBAction) clicked: (id)sender{
NSString *titleOfButton = [sender titleForState:UIControlStateNormal];
NSString *newLabelText = [[NSString alloc]initWithFormat:@"%@", titleOfButton];
labelsText.text=newLabelText;
[newLabelText release];
}
Why do I not allocate and initialize for the titleOfButton string? Does the method I call do that for me?
Also, I’m using XCode 4, but I dislike iOS 5, and such, so I do not use ARC if that matters. Please don’t say I should, I am just here to find out why this is so. Thanks!
The variable
string1is anNSStringstring literal. The compiler allocates space for it in your executable file. It is loaded into memory and initialized when your program is run. It lives as long as the app runs. You don’t need toretainorreleaseit.The lifespan of variable
string2is as long as you dictate, up to the point when youreleaseits last reference. You allocate space for it, so you’re responsible for cleaning up after it.The lifespan of variable
titleOfButtonis the life of the method-clicked:. That’s because the method-titleForState:returns anautorelease-dNSString. That string will be released automatically, once you leave the scope of the method.You don’t need to create
newLabelText. That step is redundant and messy. Simply set thelabelsText.textproperty totitleOfButton:Why use properties? Because setting this
retainproperty will increase the reference count oftitleOfButtonby one (that’s why it’s called aretainproperty), and so the string that is pointed to bytitleOfButtonwill live past the end of-clicked:.Another way to think about the use of
retainin this example is thatlabelsText.textis “taking ownership” of the string pointed to bytitleOfButton. That string will now last as long aslabelsTextlives (unless some other variable also takes ownership of the string).