How to load an NSDictionary from a file created with writeToFile?

可紊 提交于 2020-01-04 03:01:16

问题


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?


回答1:


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"];
}



回答2:


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];
}



回答3:


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.




回答4:


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) {
}


来源:https://stackoverflow.com/questions/8029426/how-to-load-an-nsdictionary-from-a-file-created-with-writetofile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!