- @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]; //安全释放旧对象
}
}
- @property (nonatomic, copy) NSNumber *count;
- (NSNumber *)count {
return _count;
}
- (void)setCount:(NSNumber *)count {
id oldValue = _count;
_count = [count copy];
[oldValue release];
}
//无需判断新旧count指针.OC runtime源代码也是这样做的.
- @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在返回值之前释放该值
- @property (assign) int count;
- (int)count {
int count;
@synchronized(self) {
count = _count;
}
return count;
}
- (void)setCount:(int)count {
@synchronized(self) {
_count = count;
}
}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。