views:

144

answers:

2

Hey guys, I had a question... I'm reading Cocoa Programming for Mac OSX and in Chapter 8 part 1, where he is writing the MyDocument.m file

What does the line

employees a;

do?

employees = [[NSMutableArray alloc] init];

is above, which means that employees is a mutable array, but I'm not sure what

employees a;

does.

I'm just taking a guess, but it looks like the code is checking to see if the argument a is already equal to the contents of employees. If it is, quit out of the function, else it will deallocate employees and set employees equal to a?

Thanks for the help in advance!

+2  A: 

It seems wrong. Objective-C has no concept of objects allocated like this, you have to do everything with pointers and alloc. It should be:

NSMutableArray *employees; // don't forget the *
employees = [[NSMutableArray alloc] init]; // allocation + constructor call

But if the book defines employees as a pointer to a NSMutableArray, it can be right:

typedef NSMutableArray *employees;
employees a;
a = [[NSMutableArray alloc] init]; // it's "a", not "employees" here

the line "employees a;" can be right with a typedef, but then the following line is wrong in both cases. You can't assign a value to a type.

My bad, it was actually employees = a.
hahuang65
@hahuang65 - you could edit your question to reflect this.
Abizern
+5  A: 

I think you are looking at page 127 of the 3rd edition.

In the init function, the employees array is initialised:

employees = [[NSMutableArray alloc] init];

This creates a mutable array in sets the employees variable to point to it.

I think you are then asking about the accessor function:

-(void)setEmployees:(NSMutableArray *)a
{
    if (a == employees)
        return;

    [a retain];
    [employees release];
    employees = a;
}

This is the function that is subsequently called whenever you change the employees array in a KVC way; This looks different from the initialisation code, because the NSMutable array that is passed in has already been created.

First, the function checks to see if it is the same array as the current employees array, if it is, there is no need to make any changes, so the function returns.

Then, the passed in array is retained, and the existing array is released. After that, the employees array is then set to point to the new array a. It is important to release the current employees array before setting it to the new array so you don't leak memory.

Hope this helps.

Abizern