Reputation: 45463
I currently have a function written called saveWorkout that saves an NSMutableArray to another NSMutableArray from a Singleton class. This function works the first run through, however, when I run it a second time, it erases what was previously stored in element 0 and replaces it with the new array (which is a collection of strings gathered when a user clicks on a table).
Here is my function:
-(IBAction)saveWorkout{
WorkoutManager *workoutManager = [WorkoutManager sharedInstance];
[[workoutManager workouts] insertObject: customWorkout atIndex: 0];
NSLog(@"%@", [workoutManager workouts]);
}
customWorkout is what initialially creates the NSMutableArray (based on what the user clicks). Thus, if my first array is comprised of blah1, blah2, those two values will be stored in the workouts array. However, if I then click blah2, blah 3, the workouts array will have two identicle arrays (blah2, blah3) and it doesn't retain the first array. Any idea why this is happening?
Here is how I form customWorkout:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *str = cell.textLabel.text;
[customWorkout insertObject:str atIndex:0];
//Test Code: Prints Array
NSLog(@"%@", customWorkout);
}
Upvotes: 0
Views: 254
Reputation: 12405
I will tell you the logical mistake that you are making....
you are using the same customWorkout object over and over again to insert in the workouts array... (so its the same pointer) whereas what you need to do is to create a copy of the customWorkout array and then insert it in the workout array ... try this instead....
[[workoutManager workouts] insertObject: [[customWorkout mutableCopy] autorelease]atIndex: 0];
this should work unless you are doing something else in your code.
Upvotes: 2
Reputation: 5703
[[workoutManager workouts] insertObject: customWorkout atIndex: 0];
does not copy the contents of customWorkout
... instead it just retains a reference to customWorkout
. So your code is simply storing multiple references to the same object, which you end up (unintentionally) editing on the second run through.
You need to either:
customWorkout
object via copy
when you store it in workouts
customWorkout
to a new NSMutableArray
instance each time after you do a saveWorkout
Either route should keep you from modifying the NSMutableArray
you store into the workouts
collection. The first option is probably more clear in terms of memory-management...
Upvotes: 0