2012-04-25 95 views
0

我正在学习iPhone开发,并面临读/写plist文件的问题。我遵循iPhone开发手册中的一个例子,但在运行时不断收到错误消息。在iPhone上阅读/写作plist iOS 5

该错误消息表示:2012-04-26 00:21:09.759 FileHandling [5915:207] - [__ NSCFDictionary ADDOBJECT:]:无法识别的选择发送到实例0x685ac40

下面是示例代码(它似乎细到我...虽然):

NSString *plistFileName = [[self documentPath] stringByAppendingPathComponent: @"Apps.plist"]; 
NSLog(@"Where is the file? => %@", plistFileName); 

if ([[NSFileManager defaultManager] fileExistsAtPath:plistFileName]) { 
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistFileName]; 

    for (NSString *category in dict) { 
     NSLog(@"%@", category); 
     NSLog(@"========="); 

     NSArray *titles = [dict valueForKey:category]; 

     for (NSString *title in titles) { 
      NSLog(@"%@", title); 
     } 
    } 
} else { 
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Apps" ofType: @"plist"];  
    NSLog(@"%@", plistPath); 
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile: plistPath]; 
    NSLog(@"Let's take a look : %@", dict); 
    NSMutableDictionary *copyOfDict = [dict mutableCopy]; 
    NSLog(@"Let's look at the mutable dictationary : %@", copyOfDict); 
    NSArray *categoriesArray = [[copyOfDict allKeys] sortedArrayUsingSelector: @selector(compare:)]; 

    for (NSString *cateogry in categoriesArray) { 
     NSArray *titles = [dict valueForKey: cateogry]; 
     NSMutableArray *mutableTitles = [titles mutableCopy]; 

     [mutableTitles addObject: @"New App Title"]; 

     [copyOfDict setObject: mutableTitles forKey:cateogry]; 
    } 

    NSString *fileName = [[self documentPath] stringByAppendingPathComponent: @"Apps.plist"]; 
    [copyOfDict writeToFile: fileName atomically:YES]; 
} 

回答

1

根据错误信息,问题是在呼叫发生的addObject:__NSCFDictionary。这意味着,在运行时,字典会收到一条消息来添加一个对象。

但是,在这段代码中,addObject:显然是发送到NSMutableArray。这可能意味着您在最后一个for循环中从dict检索的每个对象titles不是数组,而是实际上是另一个字典,您的代码只是将其称为数组。

确实,你的代码看起来确实很好,所以检查源plist的格式;用纯文本编辑器打开它。另外,您使用日志记录,因此请确认:在输出中,字典(包括根条目)由{curly = braces}表示,其中数组表示为(round parentheses)