NSString allocation and initializing

前端 未结 1 1600
面向向阳花
面向向阳花 2020-12-10 04:56

What is the difference between:

NSString *string1 = @\"This is string 1.\";

and

NSString *string2 = [[NSString alloc]initWi         


        
相关标签:
1条回答
  • 2020-12-10 05:18

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

    0 讨论(0)
提交回复
热议问题