最近項目中需要遍歷字典篩選有用信息,在遍歷時遇到一些崩潰,猛然醒悟,雖不值一提,可也是個知識點,記錄一下.
NSDictionary * dic = @{@"student":@[@"jim"], @"score":@[@"80"], @"ages":@[@"18", @"20", @"24"]};
for (id string in dic) {
NSLog(@"string = %@", string);
}
結果爲:
string = score
string = ages
string = student
二如果你直接用了value的值
NSDictionary * dic = @{@"student":@[@"jim"], @"score":@[@"80"], @"ages":@[@"18", @"20", @"24"]};
for (id string in dic) {
NSLog(@"string = %@", string[0]);
}
則會拋出異常:
-[__NSCFConstantString objectAtIndexedSubscript:]: unrecognized selector sent to instance 0x335a4c
意思是說本該是字符串的對象,卻調用objectAtIndex方法,拋出異常.正確的方法是:
for (id string in dic) {
id value = dic[string];
NSLog(@"value = %@", value);
}