Reputation: 1565
sorry if the title is worded oddly, not really sure how to say it. I am adding contents of an array of object's from a JSON into another array, so I can do use a sectioned UITableView. However, when I do the removeAllObjects
function call when I've filled enough for the first section, add them to my array, and start to load up the second, it results in the entire first section being replaces by the second section. Is NSMutableArray at fault, or is it something I am not thinking of?
weekScheduleArray = [[NSMutableArray alloc] initWithCapacity:2];
NSMutableArray *temp = [[NSMutableArray alloc] init];
for (int count = 0; count < [jsonObject count]; count++) {
if (count < 7) {
[temp addObject:[jsonObject objectAtIndex:count]];
} else if (count == 7) {
[weekScheduleArray addObject:temp];
[temp removeAllObjects];
[temp addObject:[jsonObject objectAtIndex:count]];
} else {
[temp addObject:[jsonObject objectAtIndex:count]];
}
}
[weekScheduleArray addObject:temp];
Upvotes: 0
Views: 166
Reputation: 16124
The problem is you are continuing to manipulate the exact same mutable array that you just added to the weekScheduleArray. There's a bunch of ways to solve this. You could create a copy when you add it to weekScheduleArray:
[weekScheduleArray addObject:[temp copy]];
Or you could do this:
[weekScheduleArray addObject:temp];
[temp release];
temp = [[NSMutableArray alloc] init];
[temp addObject:[jsonObject objectAtIndex:count]];
And then when you are done your for loop, remember to release temp.
Upvotes: 1
Reputation: 70135
Calling [weekScheduleArray addObject: temp]
does not add a copy of temp
to weekScheduleArray
; it adds the array itself. Therefore when you subsequently removeAllObjects
from temp
then the array in weekScheduleArray
is also empty. You can avoid the issue with:
[weekScheduleArray addObject: [temp copy]];
Upvotes: 1