项目中经常有一个NSArray、NSDictionary 中需要存储不同的类型的数据的时候怎么办?
1. 可能常用的做法是写一个model,那不就保证类型都一样了嘛
2. 使用 @encode 关键字,先看一段代码
//转换为NSValue
NSValue *value = [NSValue valueWithBytes:&locCoord objCType:@encode(CLLocationCoordinate2D)];//取值
CLLocationCoordinate2D coord; [value getValue:&coord];
那么如何在遍历NSArray、NSDictionary 的时候判断取出来的是什么类型呢,从而对应不同的操作呢,代码例子如下
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"key1",[NSNumber numberWithDouble:1.00f],@"key2",[NSNumber numberWithInt:1],@"key3",[NSNumber numberWithFloat:33.0f], @"key4", nil]; for(NSString *key in dic){ id value = [dic valueForKey:key]; if([value isKindOfClass:[NSNumber class]]){ const char * pObjCType = [((NSNumber*)value) objCType]; if (strcmp(pObjCType, @encode(int)) == 0) { NSLog(@"字典中key=%@的值是int类型,值为%d",key,[value intValue]); } if (strcmp(pObjCType, @encode(float)) == 0) { NSLog(@"字典中key=%@的值是float类型,值为%f",key,[value floatValue]); } if (strcmp(pObjCType, @encode(double)) == 0) { NSLog(@"字典中key=%@的值是double类型,值为%f",key,[value doubleValue]); } if (strcmp(pObjCType, @encode(BOOL)) == 0) { NSLog(@"字典中key=%@的值是bool类型,值为%i",key,[value boolValue]); } } }
@encode(aType) 可以返回该类型的 C 字符串(char *)的表示
@encode 和 strcmp 关键字的用法,布布扣,bubuko.com
原文:http://blog.csdn.net/songhongri/article/details/23546055