Home »
» Lazy Instantiation in Objective-C [ iphone ] [ iOS ] [ Objective C ]
Lazy Instantiation (initialisation ) , this technique is good if you have an object that only needs to be configured once and has some configuration involved that you don't want to clutter your init method.
Means in init method does not initialising the object. Initialise object somewhere else in other method of the same class may be accessor etc.
So you want an NSMutableArray property. You could alloc init it in some method before you use it, but then you have to worry about "does that method get called before I need my array?" or "am I going to call it again accidentally and re-initalize it."
So a failsafe place to do it is in the property's getter. It gets called every time you access the property.
Example
.h
@property (nonatomic, strong) NSMutableArray* myArray;
.m
@synthesize myArray = _myArray;
- (NSMutableArray*) myArray
{
if (!_myArray){
_myArray = [[NSMutableArray alloc] initWithCapacity:2];
}
return _myArray;
}
Every time you access that property, it says, "Does myArray exist? If not, create it. If it does, just return what I have."
0 comments:
Post a Comment