Difference between self.ivar and ivar?

后端 未结 4 1050
遇见更好的自我
遇见更好的自我 2020-11-22 12:11
aclass.h

@interface aClass : NSObject {
    NSString *name;
}

@property (nonatomic, retain) IBOutlet NSString *name;

@end

aclass.m         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 13:02

    name = @"Joe"

    You're accessing directly the variable, bypassing the getter method that Cocoa took the trouble of creating for you. Usually, not the wisest thing to do.

    self.name = @"Joe"

    Now your going through the method you asked cocoa to create for you. This is usually the best way.

    As a rule of thumb, use always the setter and getter provided by Cocoa, with ONE exception: dealloc. In dealloc, you should always release the variable directly, not through the getter method:

    -(void) dealloc {
       [name release]; // instead of [[self name] release]
       ...
    
       [super dealloc];
    }
    

    The reason to avoid accessors in dealloc is that if there are observers or an override in a subclass that triggers behavior, it'll be triggered from dealloc which is pretty much never what you want (because the state of the object will be inconsistent).

    OTOH, there's also a slightly more convenient syntax for declaring iVars that you might not be aware of. If you are only targeting 64bit macs, You can use properties to generate both accessor methods and the instance variable itself:

    #import 
    @interface Photo : NSObject 
    @property (retain) NSString* caption; 
    @property (retain) NSString* photographer; 
    @end
    

提交回复
热议问题