在 iOS中可以直接調用 某個對象的消息 有2種
一種是performSelector:withObject:
再一種就是NSInvocation
第一種方式比較簡單,能完成簡單的調用。但是對於>2個的參數或者有返回值的處理,那就需要做些額外工作才能搞定。那么在這種情況下,我們就可以使用NSInvocation來進行這些相對復雜的操作
NSInvocation可以處理參數、返回值。會java的人都知道反射操作,其實NSInvocation就相當於反射操作。
下面這個例子描述了如何使用NSInvocation,以下例子中如果要正常運行,需要把不存在的類進行正確填寫。
//方法簽名類,需要被調用消息所屬的類AsynInvoke ,被調用的消息invokeMethod:
NSMethodSignature *sig=[[AsynInvoke class] instanceMethodSignatureForSelector:@selector(invokeMethod:)];
//根據方法簽名創建一個NSInvocation
NSInvocation *invocation=[NSInvocation invocationWithMethodSignature:sig];
//設置調用者,在這里我用self替代
[invocation setTarget:self];
//設置被調用的消息
[invocation setSelector:@selector(invokeMethod:)];
//如果此消息有參數需要傳入,那么就需要按照如下方法進行參數設置,需要注意的是,atIndex的下標必須從2開始。原因為:0 1 兩個參數已經被target 和selector占用
NSInteger num=10;
[invocation setArgument:&num atIndex:2];
//retain 所有參數,防止參數被釋放dealloc
[invocation retainArguments];
//消息調用
[invocation invoke];
//如果調用的消息有返回值,那么可進行以下處理
//獲得返回值類型
const char *returnType = sig.methodReturnType;
//聲明返回值變量
id returnValue;
//如果沒有返回值,也就是消息聲明為void,那么returnValue=nil
if( !strcmp(returnType, @encode(void)) ){
returnValue = nil;
}
//如果返回值為對象,那么為變量賦值
else if( !strcmp(returnType, @encode(id)) ){
[invocation getReturnValue:&returnValue];
}
else{
//如果返回值為普通類型NSInteger or BOOL
//返回值長度
NSUInteger length = [sig methodReturnLength];
//根據長度申請內存
void *buffer = (void *)malloc(length);
//為變量賦值
[invocation getReturnValue:buffer];
//以下代碼為參考:具體地址我忘記了,等我找到后補上,(很對不起原作者)
if( !strcmp(returnType, @encode(BOOL)) ) {
returnValue = [NSNumber numberWithBool:*((BOOL*)buffer)];
}
else if( !strcmp(returnType, @encode(NSInteger)) ){
returnValue = [NSNumber numberWithInteger:*((NSInteger*)buffer)];
}
returnValue = [NSValue valueWithBytes:buffer objCType:returnType];
}
//還可以把 invoction 對象加到任務隊列中
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithInvocation:invoction];
[OperationQueue addOperation:operation];//OperationQueue為任務隊列
[operation release];