I have member variables in my custom UIViewController that are defined as ‘assign’ (not ‘retain’) like this:
@property (nonatomic, assign) UIButton* mSkipButton;
In my loadView method, I set the var, for instance self.mSkipButton, to an autoreleased alloc of the variable type. I then attach it to my controller’s view essentially having the view reference count and release it as needed.
This concerns me, however, that I have the pointer stored in my member var and that it could be referencing released memory if the count decrements at some point. Is it better practice to instead declare the variable as ‘retain’ and then in the viewDidUnload method release the member var (or just set it to nil to release and make sure i don’t have an address in there)?
Alternatively, could I simply set the member var to nil in viewDidUnload and not make it a retained variable?
Yes, use
retain— good instinct. InviewDidUnload, you’d typically just set it tonilvia the ivar’s setter:self.ivar = nil;I find it easier to be aware of and manage object codependencies explicitly, than to deal with issues related to using
assign. You can completely avoid the issues of holding an unmanaged reference.Arguments can be made that
assignwould usually be fine here (and it is in some cases), but usingassigncan complicate object graphs and ownership for anyone working with the class. As program complexity grows (and the libraries you depend on change), it becomes increasingly difficult to track lifetimes of unmanaged references. Things tend to break, or operate differently on different hardware and software combinations. Attempting to manage the lifetime of an unmanaged object over a complex program or in a concurrent context is self abuse. Guaranteeing defined and predictable behavior/operation reduces bug counts.