问题描述
我只想知道这两行代码之间的区别:
I just want to know what is the differneve between theses two lines of code :
@property(nonatomic, retain) NSString *str;
和
@property(atomic, retain) NSString *str;
感谢,问候,tek3
Thanx,Regards,tek3
推荐答案
在引用计数的多线程环境中,原子属性是必需的,以便在线程有机会保留它们之前阻止对象消失.
Atomic properties are necessary in a reference counted multi threaded environment in order to stop objects from disappearing before a thread has a chance to retain them.
考虑一下get访问器的简单实现:
Consider the naive implementation of a get accessor:
@interface MyObject : NSObject
{
id myPropertyIVar;
}
-(id) myProperty;
@end
@implementation MyObject
-(id) myProperty
{
return myPropertyIvar;
}
// other stuff
@end
这很好,除了如果您在保留-myProperty的返回值之前释放MyObject实例,则返回值很可能会被释放.因此,像这样实现-myProperty更安全:
This is all fine except that if you release the instance of MyObject before retaining the returned value from -myProperty the returned value may well be deallocated. For this reason, it is safer to implement -myProperty like this:
-(id) myProperty
{
return [[myPropertyIvar retain] autorelease];
}
现在在单线程环境中这是完全安全的.
This is now completely safe in a single threaded environment.
不幸的是,在多线程环境中存在竞争条件.如果线程在保留增加保留计数之前的任何时间被中断,则以下任一情况都将导致您收到垃圾指针:
Unfortunately, in a multithreaded environment there is a race condition. If the thread is interrupted at any time before the retain has incremented the retain count, either of the following will cause you to receive a garbage pointer:
- MyObject的实例由另一个线程释放和释放,导致ivar被释放和释放
- myProperty由另一个线程重新分配,导致旧版本被释放并释放
由于这个原因,对属性的所有访问都必须受到锁的保护. get访问器看起来像这样.
For this reason, all accesses to the property must be protected by a lock. The get accessor looks something like this.
-(id) myProperty
{
// lock
return [[myPropertyIvar retain] autorelease];
// unlock
}
集合访问器受到类似的保护,-dealloc中的发行版也受到保护
The set accessor is similarly protected and so is the release in -dealloc
这篇关于“原子"和“非原子"之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!