如何读取和写入到NSArray plist?

问题描述:

我有几个问题的基础上阅读和编写NSArray来自plist。如何读取和写入到NSArray plist?

我在“支持文件”文件夹中创建了一个plist文件,我想用它在第一次加载时初始化应用程序数据。

这里是我的plist是什么样子:

enter image description here

然后我用这个代码来尝试plist中加载到应用程序:

NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    filePath = [documentsDirectory stringByAppendingPathComponent:kDataFile]; 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if (![fileManager fileExistsAtPath:filePath]) 
    { 
     NSString *bundle = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; 
     [fileManager copyItemAtPath:bundle toPath:filePath error:&error]; 
    } 

然后我尝试加载从数据像这样的plist文件,但似乎没有显示。

NSMutableDictionary *savedData = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath]; 
NSMutableArray *myNSArray = [[savedData objectForKey:@"KEY_Level_1"] mutableCopy]; 
savedData = nil; 

很抱歉,如果这是个简单的任务,但是我一直在寻找很多的教程,并试图找出如何,没有运气做到这一点。我现在感到非常沮丧 - 我会认为这应该是一件简单的事情。我的NSArray将包含一大堆NSDictionaries。

+0

你需要把日志语句或逐步与调试器在每个阶段,看看它失败的地方。检查您的所有路径是否设置为您的预期,查看文件是否被复制,等等。你的代码没有什么明显的错误。该文件与您的代码具有相同的大小写吗?该plist是否包含在目标中? – jrturton 2011-12-20 19:05:17

  1. 您需要检查的copyItemAtPath:toPath:error:返回值和至少记录错误,如果该方法返回false:

    if (![fileManager copyItemAtPath:bundle toPath:filePath error:&error]) { 
        NSLog(@"error: copyItemAtPath:%@ toPath:%@ error:%@", bundle, filePath, error); 
        return; 
    } 
    
  2. -[NSDictionary initWithContentsOfFile:]没有办法报告错误,如果它是失败的,你不能轻易找出原因。尝试把文件读入一个NSData并使用-[NSPropertyListSerialization propertyListWithData:options:format:error:]解析它:

    NSData *data = [NSData dataWithContentsOfFile:filePath options:0 error:&error]; 
    if (!data) { 
        NSLog(@"error: could not read %@: %@", filePath, error); 
        return; 
    } 
    NSMutableDictionary *savedData = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainers format:NULL error:&error]; 
    if (!savedData) { 
        NSLog(@"error: could not parse %@: %@", filePath, error); 
        return; 
    } 
    NSMutableArray *myNSArray = [savedData objectForKey:@"KEY_Level_1"]; 
    savedData = nil; 
    if (!myNSArray) { 
        NSLog(@"error: %@: object for KEY_Level_1 missing", filePath); 
        return; 
    } 
    

如果你这样做,你就可以更容易地看到为什么没有被加载数据。

UPDATE

在进一步检查,它看起来像你的plist*字典包含密钥“根”。 “Root”的值是包含键“KEY_Level_1”的字典。所以你需要这样做:

NSMutableArray *myNSArray = [[savedData objectForKey:@"Root"] objectForKey:@"KEY_Level_1"]; 
+0

...或'[savedData valueForKeyPath:@“Root.KEY_Level_1”]'。 – jlehr 2011-12-20 19:41:24