开发者

IOS: problem with an NSMutableArray

I have this code;

for (int i = 0; i<period+1; i++){

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
    NSDate *newData = [dataToAdd dateByAddingTimeInterval:60*60*24*j];
    j++;
    NSString *data = [dateFormatter stringFromDate:newData];
    [[appDelegate.globalArray objectAtIndex:[name intValue]]addObject:data];

    [dateFormatter release];
}

this code work fine until I go in background. appDelegate.globalArray is a global array and when I go in background I store it with NSUserDefault

- (void)applicationDidBecomeActive:(UIApplication *)application {

globalArray = [[NSMutableArray alloc] initWithArr开发者_开发百科ay:[[NSUserDefaults standardUserDefaults] objectForKey:@"globalArray"]];}

and

- (void)applicationDidEnterBackground:(UIApplication *)application{

[[NSUserDefaults standardUserDefaults] setObject:globalArray forKey:@"globalArray"];}

the loop work fine until I go in background but when I reopen the application and I enter in this loop I have an exception

"NSCFArray insertObject:atIndex:]: mutating method sent to immutable object"

why?


Is globalArrayan array of arrays? If so, then you need to ensure that each array in globalArray is an instance of NSMutableArrayas well. I believe (correct me if I'm wrong) that when you get an array back from NSUserDefaults, you always get an immutable array. The same goes for your nested arrays.

In that case, you could try the following:

- (void)applicationDidBecomeActive:(UIApplication *)application {

    NSArray *temp = [[NSArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"globalArray"]];
    NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:[temp count]];

    for (NSArray *nestedArray in temp) {
        [result addObject:[NSMutableArray arrayWithArray:nestedArray]];
    }

    // assuming globalArray is a @property retained by your class
    self.globalArray = result;

    [result release];
    [temp release];
}

There may be a more efficient way to do this, but you get my point...


I think what is happening is that you are trying to use insertObject: in a immutable array, because once you add the array to the global it gone immutable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜