Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy instantiation

Well I'm just confused when the lazy instantiation should be used. I understand the basic concept of lazy instantiation though.

" I understand that all properties start out as nil in Objective-C and that sending a message to nil does nothing, therefore you must initialize using [[Class alloc] init]; before sending a message to a newly created property. "(Lazy instantiation in Objective-C/ iPhone development)

m.file:

@property (strong, nonatomic) NSMutableArray *cards; 

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

- (void)addCard:(Card *)card atTop:(BOOL)atTop
{
    if (atTop) {
        [self.cards insertObject:card atIndex:0];
    } else {
        [self.cards addObject:card];
} }

Well, what I really don't get is when I'm supposed to use this type of instantiation? Mostly I see the code like this:

h.file:

@interface Card : NSObject

@property (strong, nonatomic) NSString *contents;

m.file:

 if([card.contents isEqualToString:self.contents]){
        score = 1;
    }

*This might be a stupid question but I'm really confused. I'm new here, Thanks.

like image 456
Toshi Avatar asked Dec 25 '13 08:12

Toshi


1 Answers

There is no reason to use Lazy Instantiation/Lazy Initialization if you find it confusing; simply initialize your instance variables/properties in the class init methods and don't worry about it.

As the object is created as a side-effect of calling the getter method, it's not immediately obvious that it is being created at all, so one alternative, which would also mean you can use the default compiler-generate getter method, is to explicitly check for it in addCard:

- (void)addCard:(Card *)card
          atTop:(BOOL)atTop
{
    if (!self.cards)
        self.cards = [NSMutableArray new];

    if (atTop) {
        [self.cards insertObject:card atIndex:0];
    } else {
        [self.cards addObject:card];
    }
}

(and removing the user-supplied getter method)

However the net-effect is the same as the code you posted, with the exception that self.cards will return nil until addCard is called, however I doubt this will cause a problem.

like image 171
trojanfoe Avatar answered Oct 24 '22 13:10

trojanfoe