3

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;
}
Ryan Detzel
  • 5,519
  • 9
  • 37
  • 49
  • It's okay, just remember to always call self.array1 inside the class, and not _array1. – Ramy Al Zuhouri Aug 28 '13 at 11:14
  • Forms like this will make it impossible to set the value to `nil` (and have `nil` returned when read), which might, occasionally, actually be the desired value. Definitely document this behavior if it'll be a public API! – Kitsune Aug 28 '13 at 11:52

2 Answers2

1

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

Community
  • 1
  • 1
David Doyle
  • 1,716
  • 10
  • 23
1

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.. )

CodenameLambda1
  • 1,299
  • 7
  • 17