Type Encodings

233 阅读2分钟

编码表

Objective-C type encodings

CodeMeaning
cchar
iAn int
sshort
llong l is treated as a 32-bit quantity on 64-bit programs.
qlong long
CAn unsigned char
IAn unsigned int
SAn unsigned short
LAn unsigned long
QAn unsigned long long
ffloat
ddouble
BA C++ bool or a C99 _Bool
vvoid
*A character string (char *)
@An object (whether statically typed or typed id)
#A class object (Class)
:A method selector (SEL)
[array typeAn array
{name=type... }A structure
(name=type... )A union
bnumA bit field of num bits
^typeA pointer to type
?An unknown type (among other things, this code is used for function pointers)

或者通过下面方法打印查看:

void lgTypes(){
    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 long));
    NSLog(@"float --> %s",@encode(float));
    NSLog(@"bool --> %s",@encode(bool));
    NSLog(@"void --> %s",@encode(void));
    NSLog(@"char * --> %s",@encode(char *));
    NSLog(@"id --> %s",@encode(id));
    NSLog(@"Class --> %s",@encode(Class));
    NSLog(@"SEL --> %s",@encode(SEL));
    int array[] = {1,2,3};
    NSLog(@"int[] --> %s",@encode(typeof(array)));
    typedef struct person{
        char *name;
        int age;
    }Person;
    NSLog(@"struct --> %s",@encode(Person));
    
    typedef union union_type{
        char *name;
        int a;
    }Union;
    NSLog(@"union --> %s",@encode(Union));

    int a = 2;
    int *b = {&a};
    NSLog(@"int[] --> %s",@encode(typeof(b)));
}

举例说明

通过clang -rewrite-objc main.m -o main.cpp
查看main.cpp文件
会有sel和imp及编码表。
sel:方法编号 就像书的目录
imp:函数指针地址 就像书的页码 image.png

上图的@、v等类型标识编码,在xcode中 command + shift + o查找调用ivar_getTypeEncoding方法也可以获取对应的编码。 以上图nickName为例,get方法:
image.png

  • nickName",@16@0:8"
    • @表示id类型返回值
    • 16:开辟16字节内存
    • @表示id类型,第一个参数方法默认带的参数self
    • 0表示从0开始 前一个@标识id 所以0-8字节
    • :表示sel 从第8字节开始,占8字节