Reputation: 1699
I want to use the following method to save NSDictionary
+ (void)writeDicToFile:(NSDictionary *)dic fileName:(NSString *)fileName
{
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
[dic writeToFile:filePath atomically:YES];
}
But for some dictionary it works and for some complex dictionary it doesn't work.
help me!
Upvotes: 3
Views: 1397
Reputation: 18865
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 []
.
Upvotes: 2
Reputation: 4551
The documentation says that :
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.
What objects are you puttin in your dictionnary ?
Put property list objects in your dictionary, then there are no reason that it does not work.
you should also see the return value for the method. ( YES or NO).
Upvotes: 0