0

我正在研究 iPhone 开发并面临读取/写入 plist 文件的问题。我遵循了 iPhone 开发书中的示例,但在运行时不断收到错误消息。

错误消息说:2012-04-26 00:21:09.759 FileHandling[5915:207] -[__NSCFDictionary addObject:]: unrecognized selector sent to instance 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];
}
4

1 回答 1

1

根据错误消息,问题出现在对addObject:on的调用中__NSCFDictionary。这意味着,在运行时,字典接收到添加对象的消息。

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

确实,您的代码确实格式正确,因此请检查源 plist 的格式是否正确;在纯文本编辑器中打开它。此外,您使用了大量的日志记录,因此请以这种方式确认:在输出中,字典(包括根条目)由 表示{curly = braces},其中数组由 表示(round parentheses)

于 2012-05-02T04:24:03.840 回答