iOS:阅读NSDictionary崩溃的应用程序

时间:2012-11-01 15:13:11

标签: ios nsdictionary

我有一个字典,我存储在另一个字典中,它本身存储在一个数组中,如下所示:

NSMutableDictionary* sectionHeights = [[NSMutableDictionary alloc]initWithObjectsAndKeys:
                [NSString stringWithFormat:@"%f", section1Height], @"Section 1 Height",
                [NSString stringWithFormat:@"%f", section2Height], @"Section 2 Height",
        nil];

        [sectionObjects addObject:
         [[NSMutableDictionary alloc] initWithObjectsAndKeys:
          @"Site Inspection Report", @"Form Name",
          @"2", @"Section Count",
          sectionHeights, @"Section Heights",
          nil]
         ];

我将数组传递给另一个类的属性值。当我尝试回读sectionHeights时,应用程序崩溃了:

//get the subSectionData
    NSDictionary* subSectionData = [sectionObjects objectAtIndex:sectionObjects.count-1];
    NSDictionary* sectionHeights = [subSectionData objectForKey:@"Section Heights"];
    for(id obj in sectionHeights) {
        NSLog(@"%@", obj);
    }

在这种情况下,sectionHeights有2个对象,NSStrings将被转换为浮点数,但是看着控制台输出,好像应用程序试图输出3个对象:

2012-11-01 10:59:26.338 OAI_Accordion[2402:c07] Section 1 Height
2012-11-01 10:59:26.339 OAI_Accordion[2402:c07] Section 2 Height
2012-11-01 10:59:26.340 OAI_Accordion[2402:c07] -[__NSCFConstantString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x9088
2012-11-01 10:59:26.341 OAI_Accordion[2402:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x9088'
*** First throw call stack:
(0x1c95012 0x10d2e7e 0x1d204bd 0x1c84bbc 0x1c8494e 0x46e8 0x2c84 0xfb817 0xfb882 0x4aa25 0x4adbf 0x4af55 0x53f67 0x225b 0x177b7 0x17da7 0x18fab 0x2a315 0x2b24b 0x1ccf8 0x1bf0df9 0x1bf0ad0 0x1c0abf5 0x1c0a962 0x1c3bbb6 0x1c3af44 0x1c3ae1b 0x187da 0x1a65c 0x1e9d 0x1dc5 0x1)
libc++abi.dylib: terminate called throwing an exception

我无法看到我在哪里设置错误所以我希望额外的眼睛可能会有所帮助。

2 个答案:

答案 0 :(得分:2)

由于循环,您的应用程序似乎崩溃了:

for(id obj in sectionHeights) {
    NSLog(@"%@", obj);
}

当你试图错误地遍历值词典时,你很可能会收到错误countByEnumeratingWithState:objects:count:

您可以使用枚举通过块循环遍历字典:

[sectionHeights enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
{
    //
    NSLog(@"key: %@ -> value: %@", key, obj);
}];

这使您可以并排访问字典键和值。您之前的实现崩溃了,因为编译器不知道如何处理您提供的上下文中的字典。

如果您更喜欢快速枚举的语法,则应通过将代码更改为:

来循环遍历字典值数组(或者如果需要,可以使用键)。
for(id obj in [sectionHeights allValues]) {
    NSLog(@"%@", obj);
}

如果您需要字典键,也可以使用[sectionHeights allKeys]。

答案 1 :(得分:1)

请试试这个:

NSDictionary* subSectionData = [sectionObjects objectAtIndex:sectionObjects.count-1];
NSDictionary* sectionHeights = [subSectionData objectForKey:@"Section Heights"];

for(id obj in [sectionHeights allValues]) {
    NSLog(@"%@", obj);
}