美文网首页iOS源码解析
Runtime:Type Encodings

Runtime:Type Encodings

作者: yehkong | 来源:发表于2017-12-20 21:23 被阅读16次

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

    • 只要可以使用sizeof()的操作的类型都可以作为@encode()的参数,并返回子类型的字符编码。

    • 下表罗列了常用的类型编码表:

    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
    • Runtime还提供了以下列表用于定义协议的方法声明中的类型修饰符:


      MethordEncoding.png

    相关文章

      网友评论

        本文标题:Runtime:Type Encodings

        本文链接:https://www.haomeiwen.com/subject/jfzkbxtx.html