I have a UIViewController that should lazily load a view and then keep it in memory as it’s re-used quite often until e.g. a memory warning occurs or I want to clean it for some other reason. In order to achieve the lazy loading, I’ve overwritten the default getter. Here’s my code:
@interface MyController {
MyView *_myView;
}
@property(nonatomic, retain) MyView *myView;
@end
@implementation MyController
@synthesize myView = _myView;
- (MyView *)myView {
if(_myView == nil) {
_myView = [[MyView alloc] init];
// some more initialization
}
return _myView;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// the main part of my interest, freeing myView again
self.myView = nil;
}
@end
Now my question is basically: Is it still correct to release myView like I did in - (void)didReceiveMemoryWarning or would I have to [_myView release]; _myView = nil; or even something completely different?
Also, is this generally the correct way of using lazy initialization or should I improve something here in general?
Your statement for releasing the memory is absolutely correct and there is no difference between two.
In this case the setter method for
myViewproperty will be called and similar to as below.for the lazy loading … I guess
-(void)viewDidDisappearfor releasing the views and others memory related stuff and-(void) loadviewto recreate them again