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 string1
is an NSString
string 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 to retain
or release
it.
The lifespan of variable string2
is as long as you dictate, up to the point when you release
its last reference. You allocate space for it, so you're responsible for cleaning up after it.
The lifespan of variable titleOfButton
is the life of the method -clicked:
. That's because the method -titleForState:
returns an autorelease
-d NSString
. 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 the labelsText.text
property to titleOfButton
:
labelsText.text = titleOfButton;
Why use properties? Because setting this retain
property will increase the reference count of titleOfButton
by one (that's why it's called a retain
property), and so the string that is pointed to by titleOfButton
will live past the end of -clicked:
.
Another way to think about the use of retain
in this example is that labelsText.text
is "taking ownership" of the string pointed to by titleOfButton
. That string will now last as long as labelsText
lives (unless some other variable also takes ownership of the string).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With