A Question about 1 line


#1

In the example in chapter 19, there is the following code for the addAssetsObject Method:

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

My question is, why is the assets mutable array instantiated that way instead of NSMutableArray *assets = [[NSMutableArray alloc] init]? This is how we learned to do it in the book. I tried it that way and my code gives me an error.


#2

If you did that, then you would be creating a local object inside the if statement, and that object be would not be accessible from outside the if statement. If assets were nil before entering the if statement, it would still be nil after the if statement.

-(void) addAssetsObject:(Asset *)a 
{
    //Is assets nil?
    if (!assets) {
        //Create the array
        NSMutableArray *assets = [[NSMutableArray alloc] init];
       // this creates a local assets object; this is wrong!
    }
    [assets addObject:a];   // assets is presumably declared as an instance variable
   // if assets were nil before the if statement, 
   // it would still be nil because the if statement would have created a local object!
}

#3

Makes sense! Thank you!