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!
The documentation says that :
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).
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
and
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:And init the object from file like this:
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 aNSArray
- 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[]
.