0

I have a property that I do not always need, therefore I don't want to instantiate it on view did load or an init method (I think). I figure I could take a lazy instantiation approach and do initialization in the getter for the property...

-(PropertyType *)myProperty {
    if (!_myProperty)
        self.myProperty = [[PropertyType alloc] init];
    return _myProperty;
}

I just have a feeling that this is a bit hacky. But it may not be. Any ideas??

-Thanks!

jgvb
  • 304
  • 5
  • 16
  • This will definitely help you http://stackoverflow.com/questions/19276229/overriding-property-getters-with-lazy-loading-in-objective-c – LC 웃 Mar 27 '15 at 17:16
  • Thanks @anishparajuli, but that is a question more about using this technique with encapsulation rather than the benefits/disadvantages of using this technique in general. – jgvb Mar 27 '15 at 17:26

1 Answers1

0

Yes, this is very common and perfectly acceptable. You can even see this in Apple's documentation.

Relatedly, the singleton model is commonly used.

As always, you want to be careful to avoid premature optimization and do this sort of thing solely as a potential performance improvement.

Community
  • 1
  • 1
DanielG
  • 2,237
  • 1
  • 19
  • 19