思考:如何判断一个NSNumer里面存的数据类型?
解答:
使用typeEncoding
每个类型有一个对应的typeEncoding值,我们获取对应的typeEncoding值即可知道。
//定义一个float类型的变量,打印它的encoding type;我们可以看到它的encoding type值是f。
float f1 = 1;
NSLog(@"encoding type :%s",@encode(typeof(f1)));//打印:encoding type :f
//打印NSNumer的 objCType:
float f2 = 1.0;
NSNumber * nb1 = [NSNumber numberWithFloat:f2];
const char * type = [nb1 objCType];
NSLog(@"type:%s",type);//打印:type:f
//用基本数据类型的encoding type 和NSNumber的 objCType对比即可
if (strcmp(type, @encode(float)) == 0) {
NSLog(@"nb1里面是float类型");
}
参考:
http://www.makaidong.com/博客园博文/20150925/22351.html
https://www.jianshu.com/p/f4129b5194c0