为什么需要Type Encodings?
我们如果要保存属性的或者方法的类型、限定符、返回值、返回值类型不能直接用name表示,因为大量的name字符串会占用空间;比如用v代表void,i代表int。
使用@encode()可以查看类型如:
char *buf1 = @encode(float);
char*buf2 =@encode(NSObject*);
先来一张Type Encodings图:
Code Meaning
c A char
i An int
s A short
l A long
q A long long
C An unsigned char
I An unsigned int
S An unsigned short
L An unsigned long
Q An unsigned long long
f A float
d A double
B A C++boolor a C99 _Bool
v A void
* A character string (char *)
@ An object (whether statically typed or typedid)
# A class object (Class)
: A method selector (SEL)
[array type] An array
{name=type...} A structure
(name=type...) A union
bnum A bit field ofnumbits
^type A pointer totype
? An unknown type (among other things, this code is used for function pointers)
另附属性修饰类型:
常用attribute name value
nonatomic "N" ""
strong/retain "&" ""
weak "W" ""
属性的类型type "T" "@TypeName", eg"@\"NSString\""
属性的实例变量Ivar "V" "Ivar_name", eg"_name"
readonly "R" ""
getter "G" "GetterName", eg"isRight"
setter "S" "SetterName", eg"setName"
assign/atomic 默认即为assign和retain
NSInvocation的使用:
NSInvocation:保存了方法所属的对象,方法名称,方法参数和方法的返回值
NSMethodSignature(方法签名):保存了方法的名称,参数,返回值,协同NSInvocation来进行消息的转发
SEL sel =@selector(test:);
NSMethodSignature *signature = [ViewController instanceMethodSignatureForSelector:@selector(test:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
//设置方法调用者
invocation.target=self;
//注意:这里的方法名一定要与方法签名类中的方法一致
invocation.selector= sel;
NSString*name =@"yanhe";
//这里的Index要从2开始,以为0跟1已经被占据了,分别是self(target),selector(_cmd)
[invocation setArgument:&name atIndex:2];
//3、调用invoke方法
[invocation invoke];
- (void)test:(NSString*)name{
NSLog(@"%@",name);
}