In order for NSDictionary
to be successfully saved all the objects it holds have to conform to NSCoding protocol.
In short that means that you have to implement
- (void)encodeWithCoder:(NSCoder *)encoder
and
- (id)initWithCoder:(NSCoder *)decoder
for all your custom classes.
A nice tutorial is here: http://www.raywenderlich.com/1914/nscoding-tutorial-for-ios-how-to-save-your-app-data
EDIT:
Once you have written you NSCoder
methods you can save data like this:
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:self];
[archiver finishEncoding];
[data writeToFile:file atomically:YES];
And init the object from file like this:
NSData *data = [[NSData alloc] initWithContentsOfFile:file];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
self = [unarchiver decodeObject];
[unarchiver finishDecoding];
You did mention having problems with json object: the thing about json object is that first you have to check its type: it can be a NSDictionary
or a NSArray
- depending on the input and format.
Common problem occours when you get an array with only one element - dictionary you are looking for. This happens if your dictionary {...}
json representation is embedded within []
.