Saturday, May 11, 2013

NSInvocation invocationWithMethodSignature example ios


invocationWithMethodSignature:

Returns an NSInvocation object able to construct messages using a given method signature.
+ (NSInvocation *)invocationWithMethodSignature:(NSMethodSignature *)signature
Parameters
signature
An object encapsulating a method signature.
Discussion of [NSInvocation invocationWithMethodSignature]
The new object must have its selector set with setSelector: and its arguments set withsetArgument:atIndex: before it can be invoked. Do not use the alloc/init approach to createNSInvocation objects.
Example of of [NSInvocation invocationWithMethodSignature]
NSMethodSignature * mySignature = [NSMutableArray
    instanceMethodSignatureForSelector:@selector(addObject:)];
NSInvocation * myInvocation = [NSInvocation
    invocationWithMethodSignature:mySignature];
Example of [NSInvocation invocationWithMethodSignature]
#import <Foundation/Foundation.h>

@interface Person : NSObject {
    NSString *name;
    NSUInteger age;
}
- (void)setName:(NSString *)personName age:(NSNumber *)personAge;
@end

@implementation Person
- (void)setName:(NSString *)personName age:(NSNumber *)personAge {
    NSLog(@"setName:%@ age:%@", personName, personAge);
    name = [personName copy];
    age = [personAge unsignedIntegerValue];
}
@end

int main() {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];            
    Person *person = [Person new];

    SEL sel = @selector(setName:age:);

    NSMethodSignature *sig = [Person instanceMethodSignatureForSelector:sel];
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:sig];

    [inv setTarget:person];
    [inv setSelector:sel];

    NSString *name = nil;
    NSNumber *age = nil;

    [inv setArgument:&name atIndex:2];
    [inv setArgument:&age atIndex:3];

    // [inv retainArguments];
    // [inv invoke];

    NSInvocationOperation *op = [[[NSInvocationOperation alloc] initWithInvocation:inv] autorelease];
    NSOperationQueue *queue = [NSOperationQueue new];
    [queue addOperation:op];

    [pool release];
    return 0;
}