Objective-C 101 (retain vs assign) NSString

前端 未结 8 1868
甜味超标
甜味超标 2020-11-29 17:19

A 101 question

Let\'s say i\'m making database of cars and each car object is defined as:

#import 

@interface Car:NSObject{
            


        
相关标签:
8条回答
  • 2020-11-29 18:10

    There's no such thing as the "scope of an object" in Objective-C. Scope rules have nothing to do with an object's lifetime — the retain count is everything.

    You usually need to claim ownership of your instance variables. See the Objective-C memory management rules. With a retain property, your property setter claims ownership of the new value and relinquishes ownership of the old one. With an assign property, the surrounding code has to do this, which is just as mess in terms of responsibilities and separation of concerns. The reason you would use an assign property is in a case where you can't retain the value (such as non-object types like BOOL or NSRect) or when retaining it would cause unwanted side effects.

    Incidentally, in the case of an NSString, the correct kind of property is usually copy. That way it can't change out from under you if somebody passes in an NSMutableString (which is valid — it is a kind of NSString).

    0 讨论(0)
  • 2020-11-29 18:12

    The self. in:

    self.name = something;
    

    is important! Without it, you are accessing the variable directly and bypassing the setter.

    The older style (correct me if I am wrong) would have been:

    [self setName:something];
    

    Anyway, this notation was the (vaguely familiar sounding) advice that I really needed when I went looking for proper @properties on NSStrings. Thanks Axel.

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