indexOfObject not returning?


#1

I tried to return the index of an Employee instance but I get an error saying "use of undeclared identifier ‘person’…"
But Why?

[code]NSMutableArray *employees = [[NSMutableArray alloc] init];

    for (int i = 0; i < 10 ; i++) 
    {
        Employee *person = [[Employee alloc] init];
        
        [person setWeight:90 + i];
        [person setHeight:1.8 -i/10.0];
        [person setEmployeeID:i]; 
        
        [employees addObject:person]; 
    }
    NSUInteger *index = [employees indexOfObject:person];[/code]

Given that all the ‘Employee’ instances were pointed to by ‘person’ I was expecting some kind of error anyway but I would appreciate someone clearing this up for me please…


#2

[quote][code]
NSMutableArray *employees = …

for (int i = 0; i < 10 ; i++)
{
Employee *person = [[Employee alloc] init]; // person defined in this scope: for () {…}

}
NSUInteger *index = [employees indexOfObject:person]; // person not defined in this scope!

[/code][/quote]
That’s because the person variable is not defined in that scope. A variable must be defined before its use.

Also, why is the index variable a pointer to an NSUInteger?


#3

Thanks ibex10…
So, object instances are bound to the scope they are created within! I forgot about that…!?!
But how come, in chapter 19, we use the ‘employee’s’ pointer(to array) containing ‘person’ objects outside the scope they were created in? Is that because we only use the ‘employee’ pointer? Because it contains the person objects, does that make it different than being a person object?

Also, How come a for/while loop uses the initialiser ’ i ’ from outside of its loop scope? Ive never thought about that til now… :confused:

Oh and I was wrong to use a pointer to an NSUinteger as you pointed out to me…

This is my revised code and it works how I expected now:

[code]for (int i = 0; i < 10 ; i++)
{
Employee *person = [[Employee alloc] init];

        [person setWeight:90 + i];
        [person setHeight:1.8 -i/10.0];
        [person setEmployeeID:i]; 
        
        [employees addObject:person]; 
        NSUInteger index = [employees indexOfObject:person];
        NSLog(@"index of object is: %lu", (unsigned long)index);
    }[/code]