views:

54

answers:

2
NSMutableArray *persons = [ [ NSMutableArray alloc ] init ];

How can I edit person attributes without doing something like:

Person *p = [ [ Person alloc ] init ];
p = [ persons objectAtIndex:0 ];
p.name = "James Foo";
[ persons replaceObjectAtIndex: ([ persons count ] - 1 )  withObject:p];

I would like to do something like:

[ persons objectAtIndex:0 ].name = "James Foo";
+6  A: 

But you can. You have to cast the generic id into your type though:

((Person*)[persons objectAtIndex:0]).name = "James Foo";

Seva Alekseyev
Or use the setter directly. `[[persons objectAtIndex:0] setName:@"Foo"]`
Chuck
So statically-type-unsafe. The C++ habits die hard...
Seva Alekseyev
+2  A: 

This example code also has a memory leak; you shouldn't need to alloc a new person instance in that case; you could just do the following if you don't want to cast anything:

Person *p = [persons objectAtIndex:0];
p.name = @"James Foo";

and you don't need to re-add it to the array since getting the object at a location doesn't remove it from the array on its own.

Kevlar
Thanks, I'm newbie on iPhone and Objective C and i'm trying to follow best practices!
Xavi Colomer
Best practices are for those who understand the rationale behind them. Try to get something out of the door first, then read up on best practices. Premature optimization, blah blah.
Seva Alekseyev