Besides the very good approach of NSUserDefaults, there is another easy way to store data from NSArray, NSDictionary, or NSData in a file. You can also use these methods:
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
accordingly (for NSDictionary):
+ (id)dictionaryWithContentsOfFile:(NSString *)path
you just need to provide a valid location path. According to the iOS Application Programming Guide, the / Library / Caches directory will be the best place to store the data that you need to keep between application launches. (see here )
To store / load a dictionary from a file called "managers" in your directoy document, you can use the following methods:
-(void) loadDictionary { //get the documents directory: NSArray *paths = NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES); NSString *cacheDirectory = [paths objectAtIndex:0]; //create a destination file name to write the data : NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", cacheDirectory]; NSDictionary* panelLibraryContent = [NSDictionary dictionaryWithContentsOfFile:fullFileName]; if (panelLibraryContent != nil) { // load was successful do something with the data... } else { // error while loading the file } } -(void) storeDictionary:(NSDictionary*) dictionaryToStore { //get the documents directory: NSArray *paths = NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES); NSString *cacheDirectory = [paths objectAtIndex:0]; //make a file name to write the data to using the //cache directory: NSString *fullFileName = [NSString stringWithFormat:@"%@/managers", cacheDirectory]; if (dictionaryToStore != nil) { [dictionaryToStore writeToFile:fullFileName atomically:YES]; } }
In any case, this approach is very limited and you need to spend a lot of extra work if you want to store more complex data. In this case, the CoreData API is very convenient.
Chris Aug 25 '10 at 13:46 2010-08-25 13:46
source share