Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert object in an NSMutableArray saved with NSUserDefaults

I have an NSMutableArray saved with NSUserDefaults. This array is my "favourite" items that the user can saves, so when i want to add one item, i need to read the array (from NSuserDefault) and save in the first free position.

I'm using this method to add a value in the NSMutableArray

-(IBAction)save{
   NSMutableArray *abc = [[NSUserDefaults standardUserDefaults] objectForKey:@"12345"];
   int n = [abc count];
   [abc insertObject:@"aaa" atIndex:n];
   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   [[NSUserDefaults standardUserDefaults] setObject:abc forKey:@"12345"];
   [defaults synchronize];
   [abc release];
}

what's the deal? That if the user call this method two times, the second time the app crashes with this log:

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

why? and why just the second time? The first time works fine!

like image 641
JAA Avatar asked Mar 17 '11 23:03

JAA


People also ask

How do I save an array in NSUserDefaults in Objective C?

You can save your mutable array like this: [[NSUserDefaults standardUserDefaults] setObject:yourArray forKey:@"YourKey"]; [[NSUserDefaults standardUserDefaults] synchronize]; Later you get the mutable array back from user defaults. It is important that you get the mutable copy if you want to edit the array later.

What types can you store natively in NSUserDefaults?

Storing Default Objects The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs.

What is NSUserDefaults in Swift?

A property list, or NSUserDefaults can store any type of object that can be converted to an NSData object. It would require any custom class to implement that capability, but if it does, that can be stored as an NSData. These are the only types that can be stored directly.

What is the class representing a mutable array in cocoa?

The NSMutableArray is a class of the Foundation Framework and it enables you to instantiate (create) mutable array objects.


1 Answers

NSUserDefaults always returns immutable objects, even if the original object was mutable. It's in the documentation for objectForKey:

The returned object is immutable, even if the value you originally set was mutable.

You will need to create a copy of the returned object before you modify it, using [NSMutableArray arrayWithArray:]

Probably also best to use the arrayForKey method of NSUserDefaults if you're retrieving an array. Docs here: https://developer.apple.com/documentation/foundation/userdefaults

like image 111
lxt Avatar answered Sep 27 '22 20:09

lxt