Objective-C中@encode的使用

今天看Mansonry的代码时,碰到一个生僻的关键字(也许只是本身没用过)。:-)编码

 

@encode  => 将给定类型编码为内部表示的字符串。code

为了方便本身查阅,顺便也写个小例子,贴在这里,实践出真知嘛。字符串

 

    NSLog(@"UIViewController : %s", @encode(UIViewController));it

    NSLog(@"CGRect : %s", @encode(CGRect));io

    NSLog(@"int : %s", @encode(int));test

    NSLog(@"float : %s", @encode(float));float

    NSLog(@"double : %s", @encode(double));方法

    NSLog(@"BOOL : %s", @encode(BOOL));co

    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"。

相关文章
相关标签/搜索