Question Regarding The Employee.m Code


#1

In the Employee.m code assets is declared in an unusual way.

[code]#import “Employee.h”
#import “Asset.h”

@implementation Employee

@synthesize employeeID;

  • (void)addAssetsObject:(Asset *)a
    {
    // Is assets nil?
    if (!assets) {

      // Create the array
      assets = [[NSMutableArray alloc] init];
    

    }
    [assets addObject:a];
    }
    [/code]

Notice
" // Create the array
assets = [[NSMutableArray alloc] init];
"

My question is: Why is it not declared in the same way that other objects are declare in the preceding chapters, for example

why not like this

" // Create the array
NSMutableArray *assets = [[NSMutableArray alloc] init];
"

This question was answered by ibex10, however I fail to understand the answer.
I can not see where it is already declared as a NSMutableArray in the Employee class.

Can someone please elaborate on this a little more.

Any answers would be greatly appreciated.


#2

That’s not unusual: the instance variable assets is (must be) declared elsewhere and addAssetsObject: method is lazily creating the array that holds the Asset objects.

If you did that:

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

Then you would create a local variable inside the if-block. Since the variables defined inside a block are not visible from outside the block, [assets addObject:a] will have no effect if global assets is nil before the if statement executes (because the if statement is creating a local assets variable, the global one remains still nil after the if statement.)


#3

Thanks so much ibex10, you guys rock, and thank god for all those who help, this stuff is not easy.