With the following code, both items in the array are the same (the last item). What am I doing wrong that is causing this array to overwrite the values? I’m trying to use 1 object so I don’t have to instantiate X number of objects.
self.myArray = [[NSMutableArray alloc] init];
MyObjClass *obj = [[MyObjClass alloc] init];
obj.firstName = @"First Name";
obj.lastName = @"Last Name";
obj.created = @"Dec 17 16:24";
[self.myArray addObject:obj];
obj.firstName = @"First Name2";
obj.lastName = @"Last Name2";
obj.created = @"Dec 18 7:41";
[self.myArray addObject:obj];
In MyObjClass.h I have @interface MyObjClass : NSObject. Is NSObject the wrong datatype?
Properties in MyObjClass.h:
@property (strong) NSString *firstName;
@property (strong) NSString *lastName;
And from MyObjClass.m:
@synthesize firstName, lastName;
The array isn’t overwriting the values, you are in your code. You have one instance of the MyObjClass. *obj is a pointer to that objects and when you add it to the array twice, the array has two indexes that point to the object you added twice.
By setting the properties on obj, you’re changing the values of that one object that both your *obj pointer and the array points to.
Why are you concerned about instantiating X objects? It sound like you want X objects which are in the array with distinct values.
Besides creating X objects, you can copy the first object, set the values then add that to the array but since you’re setting all the values anyways, I’m not sure why you just wouldn’t init a new object.
EDIT:
Based on your comment below, it looks like your concern of multiple objects is around memory management. When you add an object to an array, it retains the object so after you add it (if you’re done with it in that scope), then release or autorelease it. When the array is released, it will call release on all the objects in the array. You need n objects whether you init or copy – you still have multiple. Release them and then let the array release when it’s released.