mutating method sent to immutable object

后端 未结 4 1519
走了就别回头了
走了就别回头了 2021-02-05 14:54

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 \"add

相关标签:
4条回答
  • 2021-02-05 15:20

    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];
    
    0 讨论(0)
  • 2021-02-05 15:24

    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]; }
    
    0 讨论(0)
  • 2021-02-05 15:26

    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];
    }
    
    0 讨论(0)
  • 2021-02-05 15:34

    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.

    0 讨论(0)
提交回复
热议问题