保存/加载Plist问题

时间:2013-10-15 03:50:04

标签: ios objective-c plist

我正在尝试一些非常简单的尝试从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"];
}

谢谢!

2 个答案:

答案 0 :(得分: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试一试。祝你好运。

答案 1 :(得分:0)

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

希望它能帮助!!!