iPhone Dev - NSString Creation

后端 未结 2 1910
南方客
南方客 2021-01-28 05:14

I\'m really confused with NSStrings. Like when should I do

NSString *aString = @\"Hello\";

of should it be:

NSString *aString =         


        
2条回答
  •  离开以前
    2021-01-28 06:08

    NSString *aString = @"Hello";
    

    Will create an autoreleased string. That is, if you don't explicitly retain it, it will might disappear after your method is over (and sometimes that's totally fine). But if you want to hold on to it past that time, you'll need to retain it.

    If you create a property for that string like this

    @property (retain) NSString *aString;
    

    And then assign like this:

    self.aString = @"Hello";
    

    Then you've properly retained the string and it will stick around.

    On the other hand, using alloc, init will create a string for you with a retain count of 1, and if you don't need it past that method, you should release it.

    ****Edit: @"Hello" is not an autoreleased string, as others have pointed out. My bad. ****

提交回复
热议问题