is it possible to save NSMutableArray or NSDictionary data as file in iOS?

RAGOpoR picture RAGOpoR · Sep 30, 2010 · Viewed 22.1k times · Source

I want to save an NSMutableArray or NSDictionary as a permanent file. Then, I would like to reopen the file later.

Is this possible? If so, how can I do it?

Answer

taskinoor picture taskinoor · Sep 30, 2010

To write in file

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];

[myArray writeToFile:filePath atomically:YES];

To read from file

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:FILE_NAME];

myArray = [NSArray arrayWithContentsOfFile:filePath];

myArray will be nil if file is not present. And NSDictionary has similar methods. Please check the reference for the details of these methods.