我是否在实现中使用_property或self.property

chr*_*hrs 0 objective-c

可能重复:
self.ivar和ivar之间的区别?

假设我有以下课程

@interface
@property ( nonatomic, retain ) MyObject* property;
@end

@implementation
@synthesize property = _property;

-(id) init{
   if ((self = [super init])) {
        _property = [MyObject new];
        self.property = [MyObject new];
        NSLog(@"%@", _property.description);
        NSLog(@"%@", self.property.description);
    }
    return self;
}
@end
Run Code Online (Sandbox Code Playgroud)

什么是正确的方法?使用访问器(合成:self.property)或直接使用ivar?只是当我尝试在其他文件中使用它时,我有时会觉得使用访问器会导致错误.

tit*_*coy 5

要么没事.使用self.propertygetter或setter方法(合成或定义)调用,同时_property直接访问实例变量.

由于self.property调用方法,它可能有副作用.例如:

- (Property *)property {
    if (_property == nil) {
        _property = [[Property alloc] init];
    }
    return _property;
}
Run Code Online (Sandbox Code Playgroud)

调用self.property将创建一个新属性并_property在返回该值之前将其分配给它,如果在该类的特定实例上第一次调用_property之前访问它将指向nil self.property.

实际上,@property声明不必与实例变量相对应; 该-property方法的实现可以在每次调用时创建并返回一个新属性.