atomic,默认是atomic,
两者的区别是:修饰的属性的setter方法和getter方法不同,
atomic修饰的属性的setter和getter方法,stomic在setter方法和getter方法设置和取值的时候有一个安全锁保障,比如线程A正在取currentImage的值,线程B和C同时改动currentImage的值,这时BC线程需等A完成后才能操作
但是atomic所说的线程安全只是保证了getter和setter存取方法的线程安全,并不能保证整个对象是线程安全的。比如等线程A取出值后,线程B将对象release掉了,当线程C去操作的时候就会闪退,所以atomic只能保障线程安全,不能保证。
- (void)setCurrentImage:(UIImage *)currentImage
{
@synchronized(self) {
if (_currentImage != currentImage) {
[_currentImage release];
_currentImage = [currentImage retain];
}
}
}
- (UIImage *)currentImage
{
@synchronized(self) {
return _currentImage;
}
}
nonatomic的setter和getter方法
- (void)setCurrentImage:(UIImage *)currentImage
{
if (_currentImage != currentImage) {
[_currentImage release];
_currentImage = [currentImage retain];
}
}
- (UIImage *)currentImage
{
return _currentImage;
}
因为nonatomic不用像atomic一样等待某个线程结束后再操作,所以nonatiomic的处理速度比atomic快
————————————————————————————————
@synthesize和@dynamic,
默认是synthesize的,是系统自动实现setter或者getter方法,
dynamic需要开发者手动实现setter和getter方法,如果未实现,在运行时找不到方法就会carsh。
本文详细对比了atomic与nonatomic两种属性修饰符的区别。atomic通过加锁机制确保setter和getter方法的线程安全,适用于多线程环境;nonatomic则不提供线程保护,执行效率更高。此外,还介绍了@synthesize和@dynamic关键字的作用。
11

被折叠的 条评论
为什么被折叠?



