Reputation:
I have a NSDictionary, which contains a bunch of arrays that have NSDates for keys, each array contains a variable amount of NSStrings
Something like this:
NSDictionary
Key: 1999-whatever-whatever
Object: (Array)
"Some string"
"Some other string"
Key: 2000-whatever-whatever
Object: (Array)
"Some third string"
I have been looking in to writeToFile, but it does not seem to support NSDictionarys that have NSDates for keys, so i looked in to KeydArchiver, would this be the best aproach?
If it is, any tutorial on the topic would be helpfull.
Thanks for your time.
PS: I assume i should do the save on ApplicationWillTerminate?
Upvotes: 2
Views: 1411
Reputation: 16720
EDIT -- I didnt realize your question said iOS. So disregard the way i saved the dictionary to your desktop, but the method for saving the NSDate as string is the same.
You don't have to go into KeydArchiver if you change the way you save your NSDictionary.
NSDictionary
Key: 1999-08-13 //<----- Have this as a string in your dictionary. Not NSDate
Object: (Array)
"Some string"
"Some other string"
Key: 2000-08-13 //<------Have this as a string in your dictionary. Not NSDate
Object: (Array)
"Some third string"
When you want to save the NSDictionary to a file you can do it like so:
[MyDictionary writeToFile:@"/Users/yourUsername/Desktop/mySavedDictionary.plist" atomically:YES];
If you want to load the dictionary again:
NSDictionary *myDictionary = [NSDictionary dictionaryWithContentsOfFile:@"/Users/yourUsername/Desktop/mySavedDictionary.plist"];
After loading your dictionary, lets say you want to get the data stored at the date 2000-08-13, then you can do it like so:
First im making the assumption that the NSDate myPreviouslyDeclaredDate
is the date you want to look up in the dictionary and that its in the format yyyy-MM-dd. You can choose what ever format you want however. Use the AppleDocs as a guide.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *previouslyDeclaredDateInStringForm = [dateFormatter dateFromString:myPreviouslyDeclaredDate];
id objectNeededFromDictionary = [myDictionary objectForKey:previouslyDeclaredDateInStringForm];
Upvotes: 4
Reputation: 1271
writeToFile
only works with basic types. I've done this once creating a new dictionary where the keys are NSStrings
and then using writeToFile
. It is obvious that I have to have a method to convert the strings into my original key format when reading from the file.
Upvotes: 2