maxisme
maxisme

Reputation: 4245

Errors manipulating array of objects

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

Upvotes: 1

Views: 20

Answers (1)

trojanfoe
trojanfoe

Reputation: 122391

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

Upvotes: 2

Related Questions