0

Here is a code snippet that I attempted to use to store and retrieve a mutable dictionary in NSUserDefaults. As my values in the dictionary are custom objects, I am using the NSKeyedArchiver. When I attempt to archive or unarchive, a NSInvalidArgumentException is thrown.

// Save NSMutableDictionary to NSUserDefaults
NSData *data = [NSKeyedArchiver archivedDataWithRootObject: dataDictionary];
[[NSUserDefaults standardUserDefaults] setObject: data forKey: key];
[[NSUserDefaults standardUserDefaults] synchronize];

// Retrieve dictionary from NSUserDefaults
NSData* data = [[NSUserDefaults standardUserDefaults] objectForKey: key];
NSMutableDictionary* dataDictionary = [[NSKeyedUnarchiver unarchiveObjectWithData: data] mutableCopy];

Any help would be greatly appreciated!

Alex Wilson
  • 1,773
  • 1
  • 12
  • 18
  • I think this code is working fine. I just tried and it worked fine. Make sure that you allocate mutable dictionary again in a new dictionary obtained from `NSUserDefaults` is always immutable even if you write `mutableCopy` too – Rajan Maheshwari Oct 12 '16 at 15:08
  • 2
    Show the whole error message. My guess is that objects inside `dataDictionary` are not `NSCoding` compliant. What kind of objects are inside `dataDictionary`? – Larme Oct 12 '16 at 15:13
  • The object inside dataDictionary are custom objects. Here is the full error message `*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[customClass encodeWithCoder:]: unrecognized selector sent to instance` – Alex Wilson Oct 12 '16 at 15:16
  • That's your issue. `customClass` has to be `NSCoding` compliant, and have `encodeWithCoder:` and `initWithCoder:`. – Larme Oct 12 '16 at 15:17
  • Okay, custom objects will throw the error. Implement `encode` and `decode` in your `CustomObject` implementation class – Rajan Maheshwari Oct 12 '16 at 15:25
  • Thank you for all of your help, adding `- (id) initWithCoder:(NSCoder *)aDecoder` and `- (void) encodeWithCoder:(NSCoder *)aCoder` as well as implementing `NSCoder ` in the custom class did the trick. https://developer.apple.com/reference/foundation/nscoder – Alex Wilson Oct 12 '16 at 15:35

0 Answers0