我们可以通过编译器指令 @encode()
来获取一个给定类型的编码字符串,下表列举了各种类型的类型编码;
Code |
Meaning |
---|---|
|
A |
|
An |
|
A |
|
A
|
|
A |
|
An |
|
An |
|
An |
|
An |
|
An |
|
A |
|
A |
|
A C++ |
|
A |
|
A character string ( |
|
An object (whether statically typed or typed |
|
A class object ( |
|
A method selector ( |
[array type] |
An array |
{name=type...} |
A structure |
(name=type...) |
A union |
|
A bit field of num bits |
|
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}