iOS 类型编码(Type Encodings)

我们可以通过编译器指令 @encode() 来获取一个给定类型的编码字符串,下表列举了各种类型的类型编码;

Code

Meaning

c

char

i

An int

s

short

l

long

l is treated as a 32-bit quantity on 64-bit programs.

q

long long

C

An unsigned char

I

An unsigned int

S

An unsigned short

L

An unsigned long

Q

An unsigned long long

f

float

d

double

B

A C++ bool or a C99 _Bool

v

void

*

A character string (char *)

@

An object (whether statically typed or typed id)

#

A class object (Class)

:

A method selector (SEL)

[array type

An array

{name=type...}

A structure

(name=type...)

A union

bnum

A bit field of num bits

^type

A pointer to type

?

An unknown type (among other things, this code is used for function pointers)

重要:Objective-C 不支持long double类型,@encode(long double)返回d,和double类型的编码值一样;


举例:

    char *buf = @encode(NSObject*[12]);
    NSLog(@"encode: %s ", buf);
    buf = @encode(float[12]);
    NSLog(@"encode: %s ", buf);
    buf = @encode(float*[12]);
    NSLog(@"encode: %s ", buf);

打印信息:

2015-10-08 12:20:17.370 AppTest[8531:126859] encode: [12@] 

2015-10-08 12:20:17.371 AppTest[8531:126859] encode: [12f] 

2015-10-08 12:20:17.371 AppTest[8531:126859] encode: [12^f] 


说明:一个数组的类型编码是用一个中括号表示的,中括号是数组的成员数量和类型,上面的例子中第一个表示12个对象的数组,第二个表示12个浮点型变量的数组,第三个便是12个浮点型指针的数组;


举例:

typedef struct example {
    int* aPint;
    double  aDouble;
    char *aString;
    int  anInt;
} Example;

   char *buf = @encode(Example);
   NSLog(@"encode: %s ", buf);

打印信息:

2015-10-08 15:33:07.906 AppTest[15180:198504] encode: {example=^id*i} 


说明:结构体的类型编码是用大括号表示的,括号中,首先是结构体类型,然后跟等号,等号后面是按照先后顺序列出结构结构体成员变量的类型,上例中按照先后顺序^i表示int型指针,d表示double类型,*表示char型指针,也就是字符串;i表示int类型;另外,结构体指针和,指向结构体指针的指针的类型编码分别如下:

    char *buf = @encode(Example*);
    NSLog(@"encode: %s ", buf);
    buf = @encode(Example**);
    NSLog(@"encode: %s ", buf);

打印信息:

2015-10-08 15:55:35.642 AppTest[15968:214671] encode: ^{example=^id*i} 

2015-10-08 15:55:35.642 AppTest[15968:214671] encode: ^^{example} 


最后,对象是被视为特殊的结构体,因此它们的类型编码和结构体是类似的。将 NSObject 传参给 @encode() 得到的是{NSObject=#},NSObject
只有一个成员就是isa,是Class类型;因此等号后面就跟了一个#符号;通过下面的例子更深入了解:

@interface Book : BaseModel
{
    @private
    NSString* _privateName;
    int* aPint;
    double  aDouble;
    char *aString;
    int  anInt;

}
@property (strong, nonatomic) NSString *author;
@property (assign, nonatomic) NSUInteger pages;
@property (strong, nonatomic) Pen *pen;

+ (void)ClassMethod;
- (void)InstanceMethod;

@end

    char *buf = @encode(Book);
    NSLog(@"encode: %s ", buf);

打印信息:

2015-10-08 16:05:53.097 AppTest[16345:222706] encode: {Book=#@^id*i} 


说明:很明显,按照先后顺序依次为Class,对象,int型指针,double,c字符串,int类型



你可能感兴趣的:(ios,type,Encodings)