Search code examples
iphoneiospropertiesnsarrayivar

iOS - How to access object properties in an array properly?


Setup:

ViewController holds an MyArray of objects from the PersonClass. PersonClass has just two properties: name and age.

Problem:

When I want to read out a name property from the first object in MyArray whats the proper way to do this?

Do I have to temporarily create an instance of PersonClass like this?

PersonClass *tmp = [PersonClass alloc] init];
tmp = [MyArray objectAtIndex:0];

NSLog(@"%@", tmp.name);

Or can I refer directly to the properties of the objects in the MyArray?

Something like this:

 NSLog(@"%@", [self.contactsArray objectAtIndex:0].name); // not working

Solution

  • I'd strongly advise using

    [(PersonClass *)[MyArray objectAtIndex:0] name]
    

    instead of seemingly cleaner, but troublesome form

    [[MyArray objectAtIndex:0] name]
    

    There are two reasons for this. First of all, it's explicit for the reader what gets called on which object. Secondly, it's explicit for the compiler - if two methods share the same name, but different return values things can get nasty. Matt Gallagher at Cocoa With Love has an excellent explanation of this issue.