1

我正在尝试一些超级简单的方法来尝试从 Plist 中保存和加载,但它不起作用。如果有人想查看我的代码并让我知道出了什么问题,我将不胜感激。

- (IBAction)testSave:(id)sender {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *plistLocation = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistLocation];

    [plistDict setObject:@"test" forKey:@"test"];
    [plistDict writeToFile:plistLocation atomically: YES];
}

- (IBAction)testLoad:(id)sender {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *plistLocation = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistLocation];

    testField.text = [plistDict objectForKey:@"test"];
}

谢谢!

4

2 回答 2

0

To write the File : You are making mistake here

- (IBAction)testSave:(id)sender {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *plistLocation = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];

    // Declare Dictionary Object
    NSMutableDictionary* plistDict;

    // Check if plist file exist or not, if EXIST load data from it otherwise create new
    if([[NSFileManager defaultManager] fileExistsAtPath:plistLocation])
        plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistLocation];
    else
        plistDict = [[NSMutableDictionary alloc] init];

    [plistDict setObject:@"test" forKey:@"test"];
    [plistDict writeToFile:plistLocation atomically: YES];
}

Your Code for Reading is Correct试试看。祝你好运。

于 2013-10-15T04:26:02.880 回答
0

检查您的文档目录中是否有 data.plist。为了找出存储在 plistLocation 中的值。按照路径,然后验证你是否真的有data.plist。

希望能帮助到你!!!

于 2013-10-15T04:41:30.810 回答