Linen copy

Well, I'm just confused when I need to use a lazy instance. However, I understand the basic concept of a lazy instance.

"I understand that all properties start as nil in Objective-C and that sending a message to nil does nothing, so you must initialize with [[Class alloc] init] before sending the message to the newly created property." ( Lazy instance 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 understand when should I use this type of instance? Basically I see the code as follows:

h.file:

 @interface Card : NSObject @property (strong, nonatomic) NSString *contents; 

m.file:

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

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

+6
source share
2 answers

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

Since an object is created as a side effect of calling the getter method, it does not immediately become obvious that it is created at all, so one alternative, which also means that you can use the getter method, which generates the default compiler, must explicitly check 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 deleting the user-provided retrieval method)

However, the network effect is the same as the code you sent, except that self.cards will return nil until addCard is called, however I doubt it will cause a problem.

+3
source

When using dot notation to access your instance variables, you call your getter method on this property. Therefore, using point notation and lazy instantiation, your getter will always assert that the property is not zero before you send it a message. Therefore code for example

 [self.cards insertObject:card atIndex:0]; 

actually call a getter on self.cards; if you use dot notation on your objects and program getters accordingly, you will always ensure that your instance variables are allocated and initialized, while also clearing your init method for code that is much more important.

Lazy instance is a common practice among Objective-C programmers; I propose to enter the convention stream.

EDIT: Thanks for Raphael mentioning this in a comment earlier.

+1
source

All Articles