Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
481 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...