Unsafe_unretained vs weak


#1

Since unsafe_unretained can leave a dangling pointer is there any reason that I wouldn’t just want to use weak for any case that I want an unretained value? Can you use weak with a C primitive like int?


#2

From the FAQ in the Transitioning to ARC Release Notes (*):

It certainly looks like weak is exclusively for pointers that should be zeroed, not for primitive types.

  • phpBB can’t handle Apple URLs, apparently; there’s no way to force it to treat the URL below as one link. This is what the tinyurl expands to.

developer.apple.com/library/mac/ … index.html#//apple_ref/doc/uid/TP40011226

Edit: Bah, can’t even paste it in. Ok, if I surround it with [ url ], it’ll at least leave the text untrammeled: http://developer.apple.com/library/mac/#releasenotes/ObjectiveC/RN-TransitioningToARC/_index.html#//apple_ref/doc/uid/TP40011226


#3

The admonition there from the docs actually just refer to the (desktop) Cocoa classes that don’t support weak references, like NSWindow or NSFont. If you reference an NSWindow in a @property, use assign, and for variables inside of a function or method you should use __unsafe_unretained.

__unsafe_unretained is useful for situations where you have an object pointer in a situation where ARC doesn’t have enough control to safely manage memory, like inside of a regular C struct. That’s one reason there’s the “no object pointers in C struct” limitation, unless you decorate that point with __unsafe_unretained to let the compiler you know what you’re doing. It’s also used to break strong-reference cycles (a.k.a. retain cycles) with blocks under some specific circumstances.

But for 99.9% of daily work, weak works great and you can forget about __unsafe_unretained.