ios developer tiny share-20160908

来源:互联网 发布:淘宝上几个评价一个心 编辑:程序博客网 时间:2024/06/10 03:11
今天讲下Objective-C的属性的原子性,即Atomic相关的,以及涉及的同步问题。


Properties Are Atomic by Default

By default, an Objective-C property is atomic:

@interface XYZObject : NSObject@property NSObject *implicitAtomicObject;          // atomic by default@property (atomic) NSObject *explicitAtomicObject; // explicitly marked atomic@end

This means that the synthesized accessors ensure that a value is always fully retrieved by the getter method or fully set via the setter method, even if the accessors are called simultaneously from different threads.

Because the internal implementation and synchronization of atomic accessor methods is private, it’s not possible to combine a synthesized accessor with an accessor method that you implement yourself. You’ll get a compiler warning if you try, for example, to provide a custom setter for an atomic, readwrite property but leave the compiler to synthesize the getter.

You can use the nonatomic property attribute to specify that synthesized accessors simply set or return a value directly, with no guarantees about what happens if that same value is accessed simultaneously from different threads. For this reason, it’s faster to access a nonatomic property than an atomic one, and it’s fine to combine a synthesized setter, for example, with your own getter implementation:

@interface XYZObject : NSObject@property (nonatomic) NSObject *nonatomicObject;@end

@implementation XYZObject- (NSObject *)nonatomicObject {    return _nonatomicObject;}// setter will be synthesized automatically@end

Note: Property atomicity is not synonymous with an object’s thread safety.
Consider an XYZPerson object in which both a person’s first and last names are changed using atomic accessors from one thread. If another thread accesses both names at the same time, the atomic getter methods will return complete strings (without crashing), but there’s no guarantee that those values will be the right names relative to each other. If the first name is accessed before the change, but the last name is accessed after the change, you’ll end up with an inconsistent, mismatched pair of names.
This example is quite simple, but the problem of thread safety becomes much more complex when considered across a network of related objects. Thread safety is covered in more detail inConcurrency Programming Guide.

0 0
原创粉丝点击