我有一个要存储在另一个字典中的字典,它本身又存储在数组中,如下所示:
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
我看不到我在哪里设置错误,所以我希望对此有更多的关注。
最佳答案
看起来您的应用程序由于循环而崩溃:
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]。
关于ios - iOS:阅读NSDictionary崩溃应用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13180033/