iOS源码解析

Runtime:Type Encodings

2017-12-20  本文已影响16人  yehkong

序言:编译器把每个方法的返回类型和参数类型编码成跟该方法相关联的字符,同时编码器也对外提供了获取相应编码字符的指令——@encode()。这个机制也是为了提高Runtime的效率。

Encodelist.png
  1. 验证代码:
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"char              : %s", @encode(char));
        
        NSLog(@"int               : %s", @encode(int));
        NSLog(@"short             : %s", @encode(short));
        NSLog(@"long              : %s", @encode(long));
        NSLog(@"long long         : %s", @encode(long long));
        NSLog(@"unsigned char     : %s", @encode(unsigned char));
        NSLog(@"unsigned int      : %s", @encode(unsigned int));
        NSLog(@"unsigned short    : %s", @encode(unsigned short));
        NSLog(@"unsigned long     : %s", @encode(unsigned long));
        NSLog(@"unsigned long long: %s", @encode(unsigned long long));
        
        NSLog(@"float             : %s", @encode(float));
        NSLog(@"double            : %s", @encode(double));
        NSLog(@"BOOL              : %s", @encode(BOOL));
        NSLog(@"void              : %s", @encode(void));
        NSLog(@"char *            : %s", @encode(char *));
        NSLog(@"NSObject *        : %s", @encode(NSObject *));
        NSLog(@"[NSObject]        : %s", @encode(typeof([NSObject class])));
        NSLog(@"float *           : %s", @encode(float*));
        NSLog(@"void *            : %s", @encode(void *));
        NSLog(@"NSObject          : %s", @encode(NSObject));
        NSLog(@"NSError **        : %s", @encode(typeof(NSError **)));
        
        char* arr1[4] = {"Hello","World","!","yehkong"};
        NSLog(@"arr1[]            : %s", @encode(typeof(arr1)));
        
        NSString* arr2[3] = {@"Good",@"Morning",@"!"};
        NSLog(@"arr2[]            : %s", @encode(typeof(arr2)));
        
        typedef struct myStruct1{
            short a;
            long long b;
            unsigned long long c;
        } MyStruct;
        NSLog(@"MyStruct          : %s", @encode(typeof(MyStruct)));
        
        union MyUnion{
            int m;
            void * n;
        };
        NSLog(@"MyUnion           : %s", @encode(union MyUnion));
        
    }
}
  1. 打印确认:
console.png
上一篇下一篇

猜你喜欢

热点阅读