Lazy instantiation

Viewed 2998

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.

2 Answers
Related