I have an NSMutableDictionary, and I wrote it using
[stuff writeToFile:@"TEST" atomically:YES];
How can I retrieve it in the future?
Also, what would happen if I decide to replace my iPhone 4 with the 4S? Can my piece of written data be transferred?
I think you want something like:
[[NSMutableDictionary alloc] initWithContentsofFile:[self dataFilePath]];
You do need to obtain the correct path to store and retrieve your file, along the lines of this routine:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"TEST"];
}
First you need to define a path to write to. If you use [stuff writeToFile:@"TEST" atomically:YES];
in the iPhone simulator it will write a file called TEST in your home directory of your Mac. Use this code to save to the Documents folder in the simulator and on the iPhone
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
Here is the code you need to read and write files.
-(void)writeFileToDisk:(id)stuff
{
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
NSString *fileName = @"TEST";
NSString *fileAndPath = [documentDirPath stringByAppendingPathComponent:fileName];
[stuff writeToFile:fileAndPath atomically:YES];
}
-(void)readFileFromDisk
{
NSArray *path = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirPath = [path objectAtIndex:0];
NSString *fileName = @"TEST";
NSString *fileAndPath = [documentDirPath stringByAppendingPathComponent:fileName];
NSArray *stuff = [[NSArray alloc] initWithContentsOfFile:fileAndPath];
NSLog(@"%@",stuff);
[stuff release];
}
You can use NSUserDefaults to store your Dictionary like this:
[[NSUserDefalts standardUserDefaults] setObject:myDictionary forKey:@"myKey"];
And later you can retrieve it like this:
[[NSUserDefalts standardUserDefaults] objectForKey:@"myKey"];
Also nothing will happen if you use the same code with an iPhone 4 or an iPhone 4S.
A Swift solution
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let filePath = (documentsPath as NSString).stringByAppendingPathComponent("data.txt")
if let data = NSDictionary(contentsOfFile: filePath) {
}