Navigation bar button item callback sets weak property to nil

My context. I have a right bar button item with a selector inside the same view controller. I also have a weak, read-only, synthesized property (with a shortcut name "_myProperty" on this view controller. When the bar button item is clicked, and I enter the selector method, I see that the value of _myProperty is nil. As far as I can tell, everything is fine up through viewDidAppear with the value of this property.


When I make the property strong, it's no longer nil. This is the opposite of what I'd expect. What am I missing in my interpretation of weak and strong attributes?

Answered by junkpile in 9805022

Without seeing the code that sets the property value it's hard to say for sure, but in general, if you have a weak property holding an object reference, it will always be nil unless something else also holds a strong reference to that same object. For example, an outlet can be weak if the view to which it points is in your view hierarchy (it is held as a strong reference in some other view's subviews property). But as soon as you call removeFromSuperview on it, the strong reference goes away, the weak reference becomes nil and the object is deallocated.

I should note that I initially expect nothing to happen since I'm seeing _myProperty with a nil value before any action has taken place in my selector.

Accepted Answer

Without seeing the code that sets the property value it's hard to say for sure, but in general, if you have a weak property holding an object reference, it will always be nil unless something else also holds a strong reference to that same object. For example, an outlet can be weak if the view to which it points is in your view hierarchy (it is held as a strong reference in some other view's subviews property). But as soon as you call removeFromSuperview on it, the strong reference goes away, the weak reference becomes nil and the object is deallocated.

Navigation bar button item callback sets weak property to nil
 
 
Q