I am trying to add two objects to my array but when i inspect the array, the second object appears in the list twice. Does anyone know why?
list = [[NSMutableArray alloc] init];
Person *person = [[Person alloc] init];
// Create person 1
person.name = @"Fred";
person.gender = @"unknown";
// Append to array
[list addObject:person];
[person release];
// Create person 2
person.name = @"Bob";
person.gender = @"male";
// Append to array again
[list addObject:person];
[person release];
You’re not creating two person instances, but just one.
Either do this:
or assign a second person to a second variable.
The
personvariable still points to the first person instance. You need to change the variable to a new instance, otherwise you’re simply inserting the person twice and also overwriting its properties.