最近项目中需要遍历字典筛选有用信息,在遍历时遇到一些崩溃,猛然醒悟,虽不值一提,可也是个知识点,记录一下.
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);
}