PDA

View Full Version : Weak property attribute




Cromulent
Dec 31, 2011, 09:03 AM
I get that the strong property is equivalent to retain as per this section of the documentation:

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.spelling.property

but what is weak used for? It says that assign is equivalent to __unsafe_unretained ownership and that weak is equivalent to __weak ownership but I'm not sure I get the difference between weak and assign. Both seem to do the same thing in that neither of them specify that the object that contains the property owns the property object.

Can someone shed some light on this please?



Guiyon
Dec 31, 2011, 09:24 AM
IIRC, in 10.6/iOS 4.0 the two keywords are identical. In 10.7/iOS 5 (or 10.5 and up if using garbage collection) and up, __weak pointers are auto-zeroed when the object they are pointing to is deallocated. It's one of the keywords I loved when developing for Mac OS X and really missed when I started doing heavy iOS work. It really helps to cut down on dangling pointer-related bugs.

In a nutshell:
__unsafe_unretained - Simple assign, ARC doesn't do anything with it
__weak - Assign with auto-zeroing on deallocation

Cromulent
Dec 31, 2011, 10:46 AM
IIRC, in 10.6/iOS 4.0 the two keywords are identical. In 10.7/iOS 5 (or 10.5 and up if using garbage collection) and up, __weak pointers are auto-zeroed when the object they are pointing to is deallocated. It's one of the keywords I loved when developing for Mac OS X and really missed when I started doing heavy iOS work. It really helps to cut down on dangling pointer-related bugs.

In a nutshell:
__unsafe_unretained - Simple assign, ARC doesn't do anything with it
__weak - Assign with auto-zeroing on deallocation

Ah, fantastic. Thanks for the info.

jared_kipe
Dec 31, 2011, 12:04 PM
Basically __weak's are supposed to become nil if the object they point to becomes stale/dealloc'd.

I really like the ideas behind ARC (automatic reference counting) but I haven't really had a problem with the simple normal reference counting.

EDIT: Oh and I say 'supposed to become nil' because you can target OSX 10.6 and iOS 4.2(or so) and not have the auto zero behavior.