What are the new type qualifiers introduced with A

2019-03-10 04:48发布

问题:

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

回答1:

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



回答2:

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.



回答3:

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.