MRC Setter Getter 标准写法

  1. @property (nonatomic, retain) NSNumber *count;
- (NSNumber *)count {
    return _count;
}

- (void)setCount:(NSNumber *)count {
    if (count != _count) {
        id oldValue = _count;  //在释放旧值之前保持他,防止其他线程通过_count访问到已释放的地址
        _count = [count retain];
        [oldValue release];    //安全释放旧对象
    }
}
  1. @property (nonatomic, copy) NSNumber *count;
- (NSNumber *)count {
    return _count;
}

- (void)setCount:(NSNumber *)count {
    id oldValue = _count;
    _count = [count copy]; 
    [oldValue release];
}
//无需判断新旧count指针.OC runtime源代码也是这样做的.
  1. @property (atomic, retain) NSNumber *count;
- (NSNumber *)count {
    NSNumber *count;
    @synchronized(self) {
        count = [_count retain]; 
    }
    return [count autorelease];   
}

- (void)setCount:(NSNumber *)count {
    id oldValue;
    @synchronized(self) {
        oldValue = _count;
        _count = [count retain];
    }
    [oldValue release];
}
//http://www.cocoawithlove.com/2009/10/memory-and-thread-safe-custom-property.html
//retain + autorelease防止另一个线程中的setter在返回值之前释放该值 
  1. @property (assign) int count;
- (int)count {
    int count;
    @synchronized(self) {
        count = _count;
    }
    return count;
}

- (void)setCount:(int)count {
    @synchronized(self) {
        _count = count;
    }
}

你可能感兴趣的:(MRC Setter Getter 标准写法)