user3152741
user3152741

Reputation: 29

Is it good practice to use the getter to lazily instantiate?

I'm making a card game that needs to be reset every time the re-deal button is clicked. To do that, I am using the following logic:

- (IBAction)redealClicked:(UIButton *)sender {
self.cardGame = NULL;
self.cardGame; //re-initialize before updating UI
[self updateUI];

}

I do lazy instantiation in the getter, so I figured I could force it to lazily instantiate to reset my game. XCode is giving me a warning saying that getters should not be used for side-effects. Technically, that's exactly what I'm doing, but is lazy instantiation a special case?

As for why I'm including the line "self.cardGame," rather than just letting it lazy-instantiate when it comes up in the program: I flip some Booleans in the instantiation that [self updateUI] accesses before it first accesses self.cardGame.

Upvotes: 0

Views: 39

Answers (1)

rmaddy
rmaddy

Reputation: 318854

Doing lazy loading in the getter is just fine.

The code you posted has no need for force the lazy loading. Just do:

- (IBAction)redealClicked:(UIButton *)sender {
    self.cardGame = NULL;
    [self updateUI];
}

Presumably the updateUI method will access the property at some point. The first access will do the lazy loading. Simple.

Just keep in mind that due to the lazy loading you should never directly access the _cardGame ivar except in the cardGame getter method.

Upvotes: 2

Related Questions