objective-C的@property,atomic, retain对引用计数的影响

先看代码:

@interface ViewController()
{
    NSObject * obj_;
}
@property(retain) NSObject * obj;//注意,默认是@property(atomic, ....
@end

@implementation ViewController
@synthesize obj = obj_;

- (id)init
{
    if(self = [super init])
    {
        obj_ = [[Obj alloc] init];
    }
    
    int n = [obj_ retainCount];
    id x = self.obj;
    int n2 = [obj_ retainCount]; // n2 与 n不相等?    
    return self;
}

结论:

没有加nonatomic作为property的修饰符,默认该property即为atomic,对于atomic的property编译器在生成getter的时候会加锁并且将变量retain后autorelease,所以每次调用getter,retainCount会加一(由于是autorelease,在本次eventloop执行最后会release)。