Placement __strong and __weak - Objective-C

The compiler does not seem to have problems with the following two declarations:

NSObject * __weak weakThing; __weak NSObject *anotherWeakThing; 

Is there a difference between the two? Is the behavior like the const keyword?

I ask because the Xcode warning usually suggests ...

SomeDataType * __weak / __ strong

... when you came up with something. So I tried to follow this pattern, but wondered if there was a difference.

+8
automatic-ref-counting
source share
2 answers

No, there is no difference. There are many things with the const keyword that it can refer to in a declaration; it may apply to a pointer, or may apply to an indication of a value.

Owner definitions only make sense with pointers to objects. The object itself cannot be β€œstrong” or β€œweak”; it is a pointer to a strong or weak object. ARC only makes sense when applied directly to pointer-to-object types and affects how this pointer's lifetime affects the lifetime of an object.

Given that there is never any ambiguity as to what a property qualifier might refer to, the ARC specification allows you to place a property qualifier anywhere in the definition of an object pointer. Both of your examples are equally true. Similarly, all of the following mean the same thing:

 NSError * __autoreleasing * someObject; NSError __autoreleasing ** someObject; __autoreleasing NSError ** someObject; 

Note that the compiler complains about this:

 NSError ** __autoreleasing someObject; 

This is because you have gone beyond the definition of a pointer to an object. You can parse this text as (NSError *)* __autoreleasing someObject; . When you go to the second * , you have already determined the type of pointer, so __autoreleasing does not make any sense. Anywhere in the definition of a pointer type is good, but as soon as you switch to a pointer type to a pointer, then you are referencing something else, and that makes no sense.

+13
source share

There is a difference if you

  __weak NSObject *someWeakThing, *someSupposedlyButNotReallyWeakThing; 

because __weak will only be embarrassed about the first variable. (this is a similar error for a rookie

 NSObject* one, two; 

which, of course, will not work as "expected").

+6
source share

All Articles