@encode(BOOL) 和[NSNumber numberWithBool:true]無法判斷問題
@encode ?=> 將給定類型編碼為內部表示的字符串。
為了方便自己查閱,順便也寫個小例子,貼在這里,實踐出真知嘛。
? ??NSLog(@"UIViewController : %s", @encode(UIViewController));
? ? NSLog(@"CGRect : %s", @encode(CGRect));
? ? NSLog(@"int : %s", @encode(int));
? ? NSLog(@"float : %s", @encode(float));
? ? NSLog(@"double : %s", @encode(double));
? ? NSLog(@"BOOL : %s", @encode(BOOL));
? ? NSLog(@"long : %s", @encode(long));
? ? NSLog(@"short : %s", @encode(short));
? ? NSDictionary *numberDic = @{@"double"? : [NSNumber numberWithDouble:1.00f],
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? @"float" ? : [NSNumber numberWithFloat:2.0f],
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? @"int" ? ? : [NSNumber numberWithInt:2],
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? @"long"? ? : [NSNumber numberWithLong:2],
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? @"bool"? ? : [NSNumber numberWithBool:YES],
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? @"short" ? : [NSNumber numberWithShort:2],
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? };
? ? for(NSString *key in numberDic){
? ? ? ? NSNumber* value = [numberDic valueForKey:key];
? ? ? ? const char * pObjCType = [value objCType];
? ? ? ? if (strcmp(pObjCType, @encode(double))? == 0) {
? ? ? ? ? ? NSLog(@"double : %@", value);
? ? ? ? }
? ? ? ? if (strcmp(pObjCType, @encode(float))? == 0) {
? ? ? ? ? ? NSLog(@"float : %@", value);
? ? ? ? }
? ? ? ? if (strcmp(pObjCType, @encode(int))? == 0) {
? ? ? ? ? ? NSLog(@"int : %@", value);
? ? ? ? }
? ? ? ? if (strcmp(pObjCType, @encode(long))? == 0) {
? ? ? ? ? ? NSLog(@"long : %@", value);
? ? ? ? }
? ? ? ? if (strcmp(pObjCType, @encode(bool))? == 0) {
? ? ? ? ? ? NSLog(@"bool : %@", value);
? ? ? ? }
? ? ? ? if (strcmp(pObjCType, @encode(short))? == 0) {
? ? ? ? ? ? NSLog(@"short : %@", value);
? ? ? ? }
? ? }
這段代碼的輸出如下:
2016-11-04 16:18:56.316 test[10003:251554] UIViewController : {UIViewController=#}
2016-11-04 16:18:56.316 test[10003:251554] CGRect : {CGRect={CGPoint=dd}{CGSize=dd}}
2016-11-04 16:18:56.316 test[10003:251554] int : i
2016-11-04 16:18:56.316 test[10003:251554] float : f
2016-11-04 16:18:56.316 test[10003:251554] double : d
2016-11-04 16:18:56.317 test[10003:251554] BOOL : B
2016-11-04 16:18:56.317 test[10003:251554] long : q
2016-11-04 16:18:56.317 test[10003:251554] short : s
2016-11-04 16:18:57.268 test[10003:251554] double : 1
2016-11-04 16:18:57.268 test[10003:251554] float : 2
2016-11-04 16:18:57.268 test[10003:251554] int : 2
2016-11-04 16:18:57.268 test[10003:251554] long : 2
2016-11-04 16:18:57.269 test[10003:251554] short : 2
從上我們看出 int 被編碼為 i;float為f;等等。
這里遇到一個問題:?[NSNumber numberWithBool:YES] 在調用?objCType 方法時,返回的是"c", 而不是"B", 所以下面的if判斷并沒有打印bool相關的輸出。 針對這個問題,我做了查找,"B"表示的是一個C++ bool,Ojbective-C中BOOL確切的說是singned char, 所以調用objCType時返回的是"c"。