1

I want to build an array of objects that can be removed and added.

So first of all I have initialised the array in the .h file like this:

@property (strong, readwrite) NSMutableArray *addArray;

Then in the .m file I initialise the array if it is empty like this in the viewDidLoad:

self.addArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"likesArray"];

if ([self.addArray count] == 0) {
    NSLog(@"array is empty");

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.addArray = [[NSMutableArray alloc] initWithArray: [defaults objectForKey:@"likesArray"]];

}

I then try and add and remove objects which will look like this:

@{@"name":_name,@"genre":_genre,@"info":_info}

By doing this to add an object:

[self.addArray addObject:@{@"name":_name,@"genre":_genre,@"info":_info}];

And doing this to remove an object

[self.addArray removeObject:@{@"name":_name,@"genre":_genre,@"info":_info}];

And finally I store the array like this:

[[NSUserDefaults standardUserDefaults] setObject:self.addArray forKey:@"likesArray"];
[[NSUserDefaults standardUserDefaults] synchronize];

But I am receiving error messages like this:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'

What am I doing wrong

1 Answer 1

2

Add mutableCopy here:

self.addArray = [[[NSUserDefaults standardUserDefaults] objectForKey:@"likesArray"] mutableCopy];

as user defaults will have returned an NSArray, not NSMutableArray.

Also this code is better:

if (!self.addArray) {
    self.addArray = [NSMutableArray new];
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Maximilian See my recent edit; I don't like the "empty test" you use in your code.

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.