开发者

What is the easiest way to init / create / make an NSInvocation with target, selector and arguments?

W开发者_运维问答hat is the easiest way to make an nsinvocation with target, selector and arguments?


This page adresses several nice constructors for nsinvocation. http://www.a-coding.com/2010/10/making-nsinvocations.html, but they doesen't cover arguments.

The following code created as a category will give you a nice way to create NSInvocations easily.

.h file

@interface NSInvocation (BetterInit)

+ (id)invocationWithSelector:(SEL)selector target:(id)target arguments:(id)firstArgument, ...;

@end

.m file

@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


This class will allow you to create an NSInvocation easily for any message, with any argument types:

http://cocoawithlove.com/2008/03/construct-nsinvocation-for-any-message.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜