I’d like a critique of the following method I use to create objects:
In the interface file:
MyClass * _anObject;
...
@property (retain, nonatomic) MyClass * anObject;
In the implementation file:
@property anObject = _anObject
so far, so simple. Now let’s override the default getter:
(MyClass *) anObject {
if(_anObject == nil) {
self.anObject = [[MyClass alloc] init];
[_anObject dowWhateverInitAction];
}
return _anObject;
}
EDIT:
My original question was about creating the object only (instead of the whole life-cycle), but I’m adding the following so that it doesn’t through off anyone:
- (void) dealloc {
self.anObject = nil;
}
/EDIT
The main point of the exercise is that setter is used inside the getter. I’ve used it for all kind of objects (ViewController, myriad other types, etc.) The advantage I get is:
- An object is created only when needed. It makes the app pretty fast
(for example, there are 6-7 views in an app, only one gets created in
the beginning). - I don’t have to worry about creating an object before it’s used… it happens automatically.
- I don’t have to worry about where the object will be needed the first time… I can just access the object as if it were already there and if it were not, it just gets created fresh.
Questions:
- Does it happen to be an established pattern?
- Do you see any drawbacks of doing this?
Yes this is an established pattern. I often use lazy instantiation like this as an alternative to cluttering up
-initor-viewDidLoadwith a bunch of setup code. I would assign the value to the instance variable instead of using the synthesized setter in the event that this object ends up being created as a result of something happening in-init.