在 iOS中可以直接調(diào)用 某個(gè)對(duì)象的消息 方式有2種
- performSelector:withObject:
- NSInvocation
第一種方式比較簡(jiǎn)單弧关,能完成簡(jiǎn)單的調(diào)用束莫。但是對(duì)于>2個(gè)的參數(shù)或者有返回值的處理,處理就相當(dāng)麻煩巷懈。
第二種NSInvocation也是一種消息調(diào)用的方法该抒,并且它的參數(shù)沒(méi)有限制,可以處理參數(shù)顶燕、返回值等相對(duì)復(fù)雜的操作凑保。
1.初始化使用
-
無(wú)參數(shù)無(wú)返回值
- (void)invocation{ //根據(jù)方法創(chuàng)建簽名對(duì)象sig NSMethodSignature *sign = [[self class] instanceMethodSignatureForSelector:@selector(method)]; // 根據(jù)簽名對(duì)象創(chuàng)建調(diào)用對(duì)象invocation NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sign]; //設(shè)置target invocation.target = self; //設(shè)置selector invocation.selector = @selector(method); //消息調(diào)用 [invocation invoke]; } - (void)method { NSLog(@"method被調(diào)用"); }
有參數(shù)無(wú)返回值
- (void)invocation{
//根據(jù)方法創(chuàng)建簽名對(duì)象sig
NSMethodSignature *sign = [[self class] instanceMethodSignatureForSelector:@selector(sendMessage:name:)];
//根據(jù)簽名對(duì)象創(chuàng)建invocation
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sign];
//設(shè)置調(diào)用對(duì)象的相關(guān)信息
NSString *name = @"張三";
NSString *message = @"發(fā)送一條消息";
//參數(shù)必須從第2個(gè)索引開始,因?yàn)榍皟蓚€(gè)已經(jīng)被target和selector使用
[invocation setArgument:&name atIndex:2];
[invocation setArgument:&message atIndex:3];
invocation.target = self;
invocation.selector = @selector(sendMessage:name:);
//消息調(diào)用
[invocation invoke];
}
- (void)sendMessage:(NSString*)message name:(NSString*)name{
NSLog(@"%@ %@",name,message);
}
-
有參數(shù)有返回值
- (void)invocation{ //根據(jù)方法創(chuàng)建簽名對(duì)象sig NSMethodSignature *sign = [[self class] instanceMethodSignatureForSelector:@selector(sumNumber1:number2:)]; //根據(jù)簽名創(chuàng)建invocation NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sign]; //設(shè)置調(diào)用對(duì)象相關(guān)信息 invocation.target = self; invocation.selector = @selector(sumNumber1:number2:); NSInteger number1 = 30; NSInteger number2 = 10; [invocation setArgument:&number1 atIndex:2]; [invocation setArgument:&number2 atIndex:3]; //消息調(diào)用 [invocation invoke]; //獲取返回值 NSNumber *sum = nil; [invocation getReturnValue:&sum]; NSLog(@"總和==%zd",[sum integerValue]); } - (NSNumber*)sumNumber1:(NSInteger)number1 number2:(NSInteger)number2{ NSInteger sum = number1+number2; return @(sum); }
2.常見方法及屬性
- NSInvocation其他常見方法屬性
//保留參數(shù)涌攻,它會(huì)將傳入的所有參數(shù)以及target都retain一遍
- (void)retainArguments
// 判斷參數(shù)是否存在,調(diào)用retainArguments之前欧引,值為NO,調(diào)用之后值為YES
@property (readonly) BOOL argumentsRetained;
// 設(shè)置消息返回值
- (void)setReturnValue:(void *)retLoc;
- NSMethodSignature其他常見方法屬性
// 方法參數(shù)個(gè)數(shù)
@property (readonly) NSUInteger numberOfArguments;
// 獲取方法的長(zhǎng)度
@property (readonly) NSUInteger frameLength;
// 是否是單向
- (BOOL)isOneway;
// 獲取方法返回值類型
@property (readonly) const char *methodReturnType NS_RETURNS_INNER_POINTER;
// 獲取方法返回值的長(zhǎng)度
@property (readonly) NSUInteger methodReturnLength;