简体   繁体   中英

mutating method sent to immutable object

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];

}

As the documentation for NSUserDefaults says: "Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value." Whenever you want to change a collection you get from NSUserDefaults you have to get the immutable version, make a mutableCopy , modify that, and set it back again.

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

- (IBAction)save:(id)sender {

   NSMutableArray *placesT = nil;
   NSArray *tempArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"placesT"];

   if (tempArray) {
      placesT = [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 release];
}

placeT是一个不可更改的数组,可以始终将placesT始终设置placesT一个可变对象,也可以使用以下代码。

NSMutableArray *placesT= [[[NSUserDefaults standardUserDefaults] objectForKey:@"placesT"] mutableCopy];

This should work:

-(IBAction) save: (id) sender {

 NSMutableArray *placesT= [[NSMutableArray alloc]initWithArray:[[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]; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM