0

i am trying to add an object into a nsuserdefault, but i get this crash "[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object" its crashing on this line: [currentFav addObject:incomingBabe];

I have no idea why its crashing, its working on my other project.

here is my code

-(IBAction)favorite {
    NSUserDefaults *standardDefault = [NSUserDefaults standardUserDefaults]; 
    NSMutableArray *currentFav = [[NSUserDefaults standardUserDefaults]objectForKey:@"fav"];
    NSLog(@"strings stored = %@",currentFav);
    NSMutableArray *newFav = [NSMutableArray arrayWithObject:[NSString stringWithFormat:@"bikini%02d.jpeg",self.currentNumber]];

if (currentFav == NULL){
   currentFav = [[NSMutableArray alloc]init];
  }
  for(NSString *incomingBabe in newFav){
  BOOL hasStringAlready = NO;
  for(NSString *currentFavorite in currentFav){
  if([currentFavorite isEqualToString:incomingBabe]){
    hasStringAlready = YES;
    NSLog(@"has string already");
    break;
    }
  }
if (!hasStringAlready) {
  [currentFav addObject:incomingBabe];
  hasStringAlready = YES;
  }
}

 [standardDefault setObject:currentFav forKey:@"fav"];
 [standardDefault synchronize];
}

2 Answers 2

2

Basically it says you are trying to use a method from NSMutableArray on NSArray.

This is because "Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value."

NSMutableArray *currentFav = [[NSUserDefaults standardUserDefaults]objectForKey:@"fav"];

will return an array, not mutable array. You should make a mutable copy of it.

NSMutableArray *currentFav = [[[NSUserDefaults standardUserDefaults]objectForKey:@"fav"] mutableCopy];
Sign up to request clarification or add additional context in comments.

Comments

0

You can get the reason of your problem from 1 floor. You can use his method to solve your problem, or like this:

NSMutableArray *currentFav = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults]objectForKey:@"fav"]];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.