使用目标,选择器和参数进行nsinvocation的最简单方法是什么?
答案 0 :(得分:3)
此页面为nsinvocation提供了几个很好的构造函数。 http://www.a-coding.com/2010/10/making-nsinvocations.html,但它们不包括论据。
以下作为类别创建的代码将为您提供一种轻松创建NSInvocations的好方法。
@interface NSInvocation (BetterInit)
+ (id)invocationWithSelector:(SEL)selector target:(id)target arguments:(id)firstArgument, ...;
@end
@implementation NSInvocation (BetterInit)
+ (id)invocationWithSelector:(SEL)selector target:(id)target arguments:(id<NSObject>)firstObject, ... {
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]];
[invocation setTarget:target];
[invocation setSelector:selector];
id eachObject;
va_list argumentList;
int index = 2; // should start at 2 since 0 and 1 is reserved _self and _cmd
// The first argument isn't part of the varargs list
if (firstObject) {
[invocation setArgument:&firstObject atIndex:index];
index ++;
// Start scanning for arguments after firstObject.
va_start(argumentList, firstObject);
// As many times as we can get an argument of type "id"
while(eachObject = va_arg(argumentList, id)) {
[invocation setArgument:&eachObject atIndex:index];
index ++; // Increase index
}
va_end(argumentList);
}
NSAssert(index == [[invocation methodSignature] numberOfArguments], @"you should have same number of arguments as methodsselector");
return invocation;
}
@end
答案 1 :(得分:0)
该类允许您轻松地为任何消息创建NSInvocation,具有任何参数类型:
http://cocoawithlove.com/2008/03/construct-nsinvocation-for-any-message.html