Sunday, June 30, 2013

mutating method sent to immutable object NSUserDefaults http://stackoverflow.com/questions/5790715/mutating-method-sent-to-immutable-object

http://stackoverflow.com/questions/5790715/mutating-method-sent-to-immutable-object

mutating method sent to immutable object NSUserDefaults


When I use this method first time it works fine, but when I called it second time I get the error "mutating method sent to immutable object". The problem is at line with "addObject" command.

  -(IBAction) save: (id) sender{    NSMutableArray *placesT= [[NSUserDefaults standardUserDefaults] objectForKey:@"placesT"];    if (!placesT) {      placesT=[[[NSMutableArray alloc] init] autorelease];  }    [placesT addObject: [NSString stringWithFormat:@"%@", tagF.text] ];    NSUserDefaults *tUD=[NSUserDefaults standardUserDefaults];  [tUD setObject:placesT forKey:@"placesT"];  [tUD synchronize];    [self dismissModalViewControllerAnimated:YES];

}


That is because the object stored in the NSUserDefaults is not the mutableArray but a normal array.

  -(IBAction) save: (id) sender{       NSMutableArray *placesT= nil;     NSrray *tempArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"placesT"];    if (tempArray) {      placeT = [tempArray mutableCopy];  } else {      placesT=[[NSMutableArray alloc] init];  }    [placesT addObject: [NSString stringWithFormat:@"%@", tagF.text] ];    NSUserDefaults *tUD=[NSUserDefaults standardUserDefaults];  [tUD setObject:placesT forKey:@"placesT"];  [tUD synchronize];    [self dismissModalViewControllerAnimated:YES];  [placesT releae];  }
   placesT is a non mutable array, either always set placesT a mutable object always or use following code.
  NSMutableArray *placesT= [[[NSUserDefaults standardUserDefaults] objectForKey:@"placesT"] mutableCopy];

No comments:

Post a Comment