So I had a project that supported iOS 4, so all my IBOutlets were __unsafe_unretained
even IBOutlets that were in the nib but outside the controllers main view (Separate View in the same nib) and all worked great.
So the time has come and now the client wants to support only iOS 5 so our team changed all the __unsafe_unretained
IBOutlets for __weak IBOutlets
but now the IBOutlets that are not inside the main view are set to nil
(except in viewdidload
) so we are unable to add them later.
If I think about it, it makes sense because if no view (main view) is retaining those IBOutlets they should be deallocated and zeroed (I don't know if that is the correct word), so the solution is to remove the __weak
from those IBOutlets
But what doesn't make sense to me is Why the different behavior between unsafe_unretained
and weak
, in my head the unsafe_unretained
ones should be deallocated and when the app tries to access them, they should point to an invalid reference and then the app should crash.
I thought that unsafe__unretained was the same as weak but without the zeroing.
Am I missing something here?
Thanks.
I thought that unsafe__unretained was the same as weak but without the zeroing.
It is, yes.
When Cocoa loads the nib, it creates all the objects autoreleased, so they are still there when viewDidLoad
is invoked. However, the autorelease pool has a lifetime that ends when control returns to the run loop. At this point all the objects that aren't owned by anything will go away so any weak outlets will be zeroed at that point.
For most outlets, this is not a problem because objects in the NIB are already generally owned by something anyway. So, for instance, a button in a view is owned by its parent view. Having strong outlets that point to that button are therefore overkill or worse might result in a retain cycle.
Top level objects obviously don't have a parent view to own them so they need to be owned by something else e.g. a controller or "File's Owner". If you are finding stuff disappears, you need to create a strong IBOutlet for it in File's owner.
For more detail, see Apple's docs.
For future searchers who come across this question, I think CRD's Stackoverflow answer to a similar question may explain. Even though the object has been deallocated, the memory that's referenced by the unsafe unretained pointer (which contains the actual object data) is not necessarily zeroed, so things may appear to behave properly until that memory is actually reused/modified/zeroed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With