将NSDictionary添加到NSArray时出现奇怪的错误

时间:2011-04-26 11:15:00

标签: iphone objective-c nsarray nsdictionary

今天我的应用程序中出现了一个非常奇怪的错误:

NSMutableDictionary *testLocal = [[NSMutableDictionary alloc] init];
[testLocal setObject:@"Test" forKey:@"title"];
[testLocal setObject:@"test notification" forKey:@"body"];
[testLocal setObject:@"1" forKey:@"repeat"];
[testLocal setObject:@"26.04.2011 - 12:53" forKey:@"start"];

NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:[saver read]];
[[dict objectForKey:@"content"] addObject:testLocal]; //Crashes here! (SIGABRT)

方法[saver read]返回:

{
    content =     (
                {
            body = "test notification";
            repeat = 1;
            start = "26.04.2011 - 13.06";
            title = Test;
        }
    );
}

所以我没有看到错误,因为我写的dict是可变的,键“content”是一个数组。

提前致谢。 mavrick3。

[saver read]:

- (NSDictionary *)read {
    return [[NSDictionary alloc] initWithContentsOfFile:[self filePath]];
}

3 个答案:

答案 0 :(得分:2)

尝试检查[dict objectForKey:@"content"]返回的对象是什么类。那么事情会更加清晰。我怀疑它没有返回NSMutableArray个实例,而是返回其他内容,很可能是NSArray,它不响应方法addObject:

答案 1 :(得分:1)

来自objectForKey的Apple文档:

与Key关联的值,如果没有值与Key关联,则 nil 。所以您的代码可能如下所示

if([dict objectForKey:@"content"] != nil && [[dict objectForKey:@"content"] isKindOfClass:[NSMutableArray class]] )
{
  [[dict objectForKey:@"content"] addObject:testLocal];
} 
else
{
   [dict setObject: textLocal forKey: @"content"];
}

答案 2 :(得分:0)

要添加字典的数组是否可变?