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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.设计模式是什么? 你知道哪些设计模式,并简要叙述?设计模式是一种编码经验,就是用比较成熟的逻辑去处理某一种类型...
    龍飝阅读 6,632评论 0 12
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,898评论 1 32
  • 属性修饰符简述 ios5之前是MRC,内存需要程序员进行管理,ios5之后是ARC,除非特殊情况,比如C框架或者循...
    咖啡绿茶1991阅读 4,140评论 0 2
  • 307、setValue:forKey和setObject:forKey的区别是什么? 答:1, setObjec...
    AlanGe阅读 5,529评论 0 1
  • 案例基本情况:一年级学生男生,聪明,具有一定的学习能力,课堂听讲一般,家庭作业经常不做,班主任联系家长打电话...
    LOVE小马老师阅读 3,652评论 0 2

友情链接更多精彩内容