试图写入.plist文件,但它无法正常工作

时间:2012-05-23 00:59:37

标签: iphone ios plist

我正在尝试将一个非常简单的数据写入.plist文件,我已经检查了各种代码示例,但我很难让它工作。

首先,有创建文件本身并返回路径的方法:

-(NSString *)getFilePath{
    NSArray *thePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [[thePath objectAtIndex:0] stringByAppendingPathComponent:@"events.plist"];
}

然后这是我连接到按钮的动作。它目前只插入一行虚拟数据。或者至少,这就是我想要做的事情。

- (IBAction)saveData:(id)sender {
    NSArray *data = [[NSArray alloc] initWithObjects:@"E3 Expo", @"05-06-2012", nil];
   [data writeToFile:[self getFilePath] atomically:YES];
}

但它不起作用。我通过Xcode中的管理器检查了用户文档的目录,并且没有在“Documents”文件夹中创建任何内容。

任何帮助将不胜感激。 :)

1 个答案:

答案 0 :(得分:0)

您必须将字典设置为根plist对象。

[编辑:如果您看不到该文件,请使用NSFileManager]

创建该文件
NSError *error;
NSString *plistPath = [self getFilePath];

NSArray *data = [[NSArray alloc] initWithObjects:@"E3 Expo", @"05-06-2012", nil];
NSDictionary *plistDict = [NSDictionary dictionaryWithObject: data forKey: @"array"];
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict
                                                               format:NSPropertyListXMLFormat_v1_0
                                                     errorDescription:&error];
if(plistData) {
    //not necessary
    if ([[NSFileManager defaultManager] fileExistsAtPath: plistPath]) {
        [[NSFileManager defaultManager] removeItemAtPath: plistPath error: &error];
    }
    [[NSFileManager defaultManager] createFileAtPath: plistPath contents:plistData attributes: nil];
    //necessary
    [plistData writeToFile: plistPath atomically:YES];
}
else {
    NSLog(error);
    [error release];
}
//also release data, since you retained it (sorry, memory management OCD)
[data release];

Based on Apple documentation - scroll to Write Out the Property List