0

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

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

我看不出我在哪里设置错误,所以我希望更多的关注它可能会有所帮助。

4

2 回答 2

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]。

于 2012-11-01T15:48:08.787 回答
1

请试试这个:

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

for(id obj in [sectionHeights allValues]) {
    NSLog(@"%@", obj);
}
于 2012-11-01T15:44:13.863 回答