What are the new type qualifiers introduced with ARC?

后端 未结 3 1375
天涯浪人
天涯浪人 2021-02-01 21:44

Automatic Reference Counting (ARC) introduces some new type qualifiers. I\'ve seen __strong and __weak, but what do they do?

相关标签:
3条回答
  • 2021-02-01 21:51

    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.

    0 讨论(0)
  • 2021-02-01 21:52

    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.

    0 讨论(0)
  • 2021-02-01 22:17

    __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.

    0 讨论(0)
提交回复
热议问题