addAssetObject:(Asset *)a


#1

Hi,

Can someone please provide me with a detailed explanation of what exactly is happening here. Thanks.

Also in the book when they say “you can do this when the original object is (an employee) is first created, or you can be lazy and wait until the collection is needed” what does that mean??

-(void)addAssetsObject:(Asset *)a
{
//is assets nil?
if (!assets) {
assets = [[NSMutableArray alloc]init];
}
return [assets addObject:a];
}


#2

[quote]-(void)addAssetsObject:(Asset *)a { //is assets nil? if (!assets) { assets = [[NSMutableArray alloc]init]; } return [assets addObject:a]; }[/quote]
The above code first checks the see if there is an assets array to add an asset to; it then adds the asset object to the array.

If there is no array (the value of assets variable is nil), it creates an array object and assigns the address of the object to the assets variable. Next time around, it won’t create an array because the value of the assets variable is no longer nil. This is a lazy-way of doing things because the array object is not created until the moment it is needed. If you don’t add any assets, why create an array to hold them and waste memory resources.

Alternatively, the array can be created up front during the initialisation of the Employee object:

@implementaion Employee
...
- (id)init...
{
    ...
    assets = [[NSMutableArray alloc] init];
    ...
}
...

Then addAssetsObject: simplifies to:

-(void)addAssetsObject:(Asset *)a { return [assets addObject:a]; }
Both methods have pros and cons. Can you think of any?


#3

thanks ibex10!