What properties should I set to nil in viewDidUnload?
-
02-07-2021 - |
Question
I don't know if I'm using viewDidUnload properly. Should I release all stuff I declare in my .h file?
Here is how I'm doing it now:
@property (strong, nonatomic) Readability *wrapper;
@property (strong, nonatomic) ArticleModel *article;
@property (strong, nonatomic) Woho *wohoItem;
@property (strong, nonatomic) FeedItem *item;
@property (unsafe_unretained, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) NSMutableArray *picturesArray;
@property (unsafe_unretained, nonatomic) IBOutlet UILabel *headTitleLabel;
and in viewDidUnload:
- (void)viewDidUnload
{
[self setHeadTitleLabel:nil];
[self setScrollView:nil];
self.picturesArray = nil;
self.item = nil;
self.article = nil;
self.wohoItem = nil;
self.wrapper = nil;
}
Is this the right thing to do?
Probably not, because my app crash on every memory warning.
Thanks!
Solution
When a low-memory warning occurs, the UIViewController
class purges its views if it knows it can reload or recreate them again later. If this happens, it also calls the viewWillUnload
and viewDidUnload
methods to give your code a chance to relinquish ownership of any objects that are associated with your view hierarchy, including objects loaded from the nib file, objects created in your viewDidLoad method, and objects created lazily at runtime and added to the view hierarchy.
OTHER TIPS
developer.apple says:
When a view controller receives a memory warning (didReceiveMemoryWarning), it should relinquish ownership of resources that are currently not needed and that can be recreated later if required. One such resource is the view controller's view itself. If it does not have a superview, the view is disposed of (in its implementation of didReceiveMemoryWarning, UIViewController invokes [self setView:nil])
The programming guide is here
Set all IBOutlets to nil in - (void)viewDidUnload. If you are using iOS 5 the better use 'weak' reference for IBOutlets.
I advise you to make Control-Drag of each iterface element from NIB(xib) or Storyboard to your interface code. It will generate all fields for you.