我已經與這部分代碼的方法:的NSDictionary for循環異常
NSDictionary *tmpDict = [self getJsonDictionary];
NSInteger tmpID;
for (NSDictionary *d in tmpDict) {
tmpID = [[d objectForKey:@"id"] integerValue];
}
tmpDict
是具有可變大小的NSDictionary。如果tmpDict
含有至少2個對象(2 NSDictionary中)它工作得很好,但如果只包含1個對象(1 NSDictionary中)拋出此異常:
-[NSCFString objectForKey:]: unrecognized selector sent to instance 0x4e866d0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString objectForKey:]: unrecognized selector sent to instance 0x4e866d0'
爲什麼呢?如何修復如果tmpDict
只有1個對象?
可能for (NSDictionary *d in tmpDict)
是問題,當tmpDict
有1個對象d
是NSCFString
,但是爲什麼?
- UPDATE
問題是,當tmpDict
有1個項目(一個的NSDictionary)的for (NSDictionary *d in tmpDict)
採取各種鍵/值項的字典,這是異常的原因。否則,如果tmpDict
有2+項是NSDictionary的NSDictionary,它運作良好。我需要一種方法來解決這個問題,仍然使用for循環。想法?
- 更新2 *
其實這段代碼的作品,但它是多餘的:
if ([tmpObject isKindOfClass:[NSDictionary class]]) {
tmpID = [[tmpObject objectForKey:@"id"] integerValue];
tmpProp2 = [tmpObject objectForKey:@"prop2"];
tmpProp3 = [tmpObject objectForKey:@"prop3"];
tmpProp4 = [tmpObject objectForKey:@"prop4"];
} else if ([tmpObject isKindOfClass:[NSArray class]]) {
for (NSDictionary *d in tmpObject) {
tmpID = [[d objectForKey:@"id"] integerValue];
tmpProp2 = [d objectForKey:@"prop2"];
tmpProp3 = [d objectForKey:@"prop3"];
tmpProp4 = [d objectForKey:@"prop4"];
}
}
它需要改進。
WRT更新2:唯一的改進是你可以從字典中獲取項目。否則,這看起來不錯。 –