Ryan Detzel
Ryan Detzel

Reputation: 5599

Is it okay to lazy initialization/load all objects?

I find myself lazy initialization all my functions now. It just feels more natural and it allows me to to stop writing setup functions. Is this bad by design? What are the pitfalls?

@property (nonatomic, strong) NSMutableArray *array1;

-(NSMutableArray *)array1{
   if (!_array1){
       _array1 = [[NSMutableArray alloc] init];
   }
   return _array1;
}

I then find myself doing things like:

-(NSMutableArray *)array1{
   if (!_array1){
       _array1 = [[NSMutableArray alloc] init];
       // read a file
       // [_array addObject:newObject];
   }
   return _array1;
}

Upvotes: 3

Views: 918

Answers (2)

CodenameLambda1
CodenameLambda1

Reputation: 1299

Doing lazy loading for everything, may cause runtime slow down of user-interaction because the app may get busy every now and then to load stuff into memory. Use it only when required (i.e. when an object requires lot of memory in for complete loading.. )

Upvotes: 1

David Doyle
David Doyle

Reputation: 1716

It is and it isn't. Lazy instantiation is fine as a concept, but you have to be careful. For example, if two different threads attempt to access either of your variables at the same time, you may end up with having two different lazily instantiated variables. See the answer here:

Thread safe lazy initialization on iOS

Upvotes: 1

Related Questions