NSMutableSet *set = [NSMutableSet set]; NSString *stuff = @"Stuff"; SEL selector = @selector(addObject:); NSMethodSignature *sig = [set methodSignatureForSelector:selector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; [invocation setTarget:set]; [invocation setSelector:selector]; //將第一個參數放在index2 [invocation setArgument:&stuff atIndex:2]; [invocation invoke];
index 0 是target(self) index 1 是selector(_cmd). 須要注意的是傳遞的是指針(&stuff),而不是變量自己。 指針
Invocation 很靈活,可是卻很慢。 code
建立一個invocation比直接調用方法會慢不少。可是執行Invocation很cheap,而且Invocation是能夠複用的。 get