I am studying memory management, and I have made a small program which manages a table object.
Here is my .h:
@interface Person : NSObject {
NSString *firstName;
NSString *lastName;
}
@property (readwrite, copy) NSString *firstName;
@property (readwrite, copy) NSString *lastName;
Here is my .m:
- (IBAction)clic2:(id)sender {
Person *pers = [[Person alloc]init];
NSMutableArray *myarray = [[NSMutableArray alloc] init];
[pers setFirstName:@"FN 1"]; // = pers.firstName
[pers setLastName:@"LN 1"]; // = pers.lastName
[myarray addObject:pers];
[pers setFirstName:@"FN 2"];
[pers setLastName:@"LN 2"];
[myarray addObject:pers];
[pers release];
for(int i = 0; i < [myarray count]; i++)
{
pers = [myarray objectAtIndex:i];
NSLog(@"%d %@ %@ %@", [myarray objectAtIndex:i], pers, pers.firstName, pers.lastName);
}
}
- (void)dealloc
{
[firstName release];
firstName = nil;
[lastName release];
lastName = nil;
[super dealloc];
}
and this is my NSLog
2011-04-28 21:40:11.568 temp[4456:903] 4495296 <Person: 0x1004497c0> FN 2 LN 2 2011-04-28 21:40:11.571 temp[4456:903] 4495296 <Person: 0x1004497c0> FN 2 LN 2
As you can see, the stored information is the same; it seems that is because myarray always stores the same memory address/content of the person in the array.
I understand from this that when I change the content of pers at the second call the system will also change the information in myarray.
How do I do this so as to not overwrite the data?
Thank you for your answers.
EDIT : This example is for 2 persons but the idea is manage an unbounded number given
EDIT2 : Thank's all for memory management explanations in this case