user3398985
user3398985

Reputation: 45

why isn't lazy instantiation used in every getter

In the stanford course Paul Hegarty prefers to use lazy instantiation. For instance he makes a private declaration of

@property (strong, nonatomic) (NSArray *)cards

and then he uses the getter to perform an initialization

- (NSArray *) cards
{
   if(!_cards) _cards = [[NSArray alloc]init]
   return _cards;
}

I'm cool with that. What I don't get though is that at another time Paul declares a public suit for a playingCard being:

 @property (strong, nonatomic) NSString *suit;

but in the implementation he doesn't perform this lazy instantiation. So I don't understand where the alloc init of the suit string happens? (suit being a pointer to an NSString - object which ought to get a place in the heap)

#import "PlayingCard.h"

@implementation PlayingCard
@synthesize suit = _suit;

- (void)setSuit:(NSString *)suit
{
    if ([@[@"♣︎", @"♠︎", @"♥︎", @"♦︎"]containsObject: suit]) {
        _suit = suit;
    }
}

- (NSString *)suit
{
    return _suit? _suit: @"?";
}
@end

Upvotes: 2

Views: 289

Answers (3)

uchuugaka
uchuugaka

Reputation: 12782

Lazy instantiation is not a panacea but can improve the object instantiation and app responsiveness if you don't spend cycles instantiating ivar objects all at once before you need them. This effect is nothing on a small simple class, but if you have a large set or array of objects, setting them all up completely at once will slow down things at one point.

To be fair the same hit could come later.

Upvotes: 1

Wayne
Wayne

Reputation: 60414

When you ask for the cards instance there is no additional information required (i.e. there are no necessary parameters). You just instantiate a PlayingCard and return it.

A suit, on the other hand, could be one of four options, so somebody needs to set that somewhere. Note that this issue is really independent of lazy initialization. It has more to do with the fact that suit expects to be initialized with a user-parameterized value.

Lazy initialization is a way to say, "don't bother creating an instance of this object until I ask for it." But in the case of suit, you don't want to create the string until the user supplies it.

Upvotes: 3

Sergey Demchenko
Sergey Demchenko

Reputation: 2954

The property is public, so he assumes that it will be set somewhere. When you set this property you can alloc, init and then set it to Playing card instance, for example:

PlayingCard *playingCard = [PlayingCard new];
[playingCard setSuit:@"spade"];

Lazy initialisation is used if property is private (so you can not initialise it outside of the class), but you don't want to initialise it in init method of the class.

Upvotes: 4

Related Questions