What are the new type qualifiers introduced with ARC?

半世苍凉 提交于 2019-12-02 19:14:50
Jacob Relkin

__strong means that on assignment, the rvalue of the expression will be retained and stored into the lvalue using primitive semantics. (To deallocate such an object, all you must do is assign it nil, the previously referenced object will be released, nil will be retained, which effectively does nothing and it's peaches and cream.)

__unsafe_unretained and __weak are similar in the sense that the address of the rvalue will be assigned to the lvalue, but if you use the __weak qualifier, this operation is guaranteed to be atomic and subject to some different semantics. One of these are that if the object that is being assigned is currently undergoing deallocation, then the assignment will evaluate to nil and that will then be atomically stored back in to the lvalue of the expression. Hence the wording __unsafe_unretained, because that operation is indeed unsafe and unretained.

__autoreleasing is like __strong except it has one caveat: The retained object is pushed onto the current autorelease pool, so you can for example obtain temporary ownership of an object to remove it from a collection and then return it back to the caller. There are other uses for this, but they mostly have to do with obtaining temporary ownership of an object.

These behaviors also present themselves in the corresponding property modifiers (strong, unsafe_unretained and weak).

See the Clang Automatic Reference Counting Technical Specification

EDIT: For those not targeting iOS 5 and therefore unable to reap the benefits of __weak, Mike Ash wrote a superb article (and implementation) on zeroing weak references which you can use instead.

NJones

Strong tells ARC to retain the property.

@property (strong,nonatomic) NSObject *object;
@property (retain,nonatomic) NSObject *object;

Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil.

@property (weak,nonatomic) NSObject *object;
@property (assign,nonatomic) NSObject *object;

Weak is only available on iOS 4.3 and up. If you want to target iOS 4.2 you need to use unsafe_unretained, that will work exactly like assign used to.

The type qualifiers are __autoreleasing, __strong, __unsafe_unretained, and __weak. The property modifiers are strong, unsafe_unretained, and weak.

Have a look at section 4 of Automatic Reference Counting in the LLVM/Clang documentation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!