How to load an NSDictionary from a file created wi

2019-07-04 06:24发布

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?

4条回答
smile是对你的礼貌
2楼-- · 2019-07-04 06:56

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.

查看更多
来,给爷笑一个
3楼-- · 2019-07-04 07:03

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) {
}
查看更多
趁早两清
4楼-- · 2019-07-04 07:13

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];
}
查看更多
做个烂人
5楼-- · 2019-07-04 07:17

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"];
}
查看更多
登录 后发表回答