1
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";
1
  • 3
    It should be @"James Foo". You need the @ sign in there. Commented Jan 14, 2010 at 20:28

2 Answers 2

6

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Or use the setter directly. [[persons objectAtIndex:0] setName:@"Foo"]
2

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.

2 Comments

Thanks, I'm newbie on iPhone and Objective C and i'm trying to follow best practices!
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.