Saturday, May 11, 2013

NSInvocation invocationWithMethodSignature example ios


Returns an NSInvocation object able to construct messages using a given method signature.
+ (NSInvocation *)invocationWithMethodSignature:(NSMethodSignature *)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
NSInvocation * myInvocation = [NSInvocation
Example of [NSInvocation invocationWithMethodSignature]
#import <Foundation/Foundation.h>

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

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

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;