0

Possible Duplicate:
Difference between self.ivar and ivar?

Let's say I have the following class

@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

What is the correct way? using accessors (synthesize: self.property) or using the ivar directly? It's just that i have sometimes felt that using the accessors caused in errors when I try to use them in other files.

4

1 回答 1

5

哪一个都好。Usingself.property调用 getter 或 setter 方法(合成或定义),同时_property直接访问实例变量。

由于self.property调用方法,它可能会产生副作用。例如:

- (Property *)property {
    if (_property == nil) {
        _property = [[Property alloc] init];
    }
    return _property;
}

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

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

于 2012-10-09T01:57:52.773 回答