Saturday, May 11, 2013

NSInvocation setArgument atIndex example ios


setArgument : atIndex :

Sets an argument of the receiver.
- (void)setArgument:(void *)buffer atIndex:(NSInteger)index
Parameters
buffer
An untyped buffer containing an argument to be assigned to the receiver. See the discussion below relating to argument values that are objects.
index
An integer specifying the index of the argument.
Indices 0 and 1 indicate the hidden arguments self and _cmd, respectively; you should set these values directly with the setTarget: and setSelector: methods. Use indices 2 and greater for the arguments normally passed in a message.
Discussion( NSInvocation setArgument atIndex example )
This method copies the contents of buffer as the argument at index. The number of bytes copied is determined by the argument size.
When the argument value is an object, pass a pointer to the variable (or memory) from which the object should be copied:
NSArray *anArray;
[invocation setArgument:&anArray atIndex:3];
This method raises NSInvalidArgumentException if the value of index is greater than the actual number of arguments for the selector.
( NSInvocation setArgument atIndex example )
- (void)hello:(NSString *)hello world:(NSString *)world
{
    NSLog(@"%@ %@!", hello, world);

    NSMethodSignature *signature  = [self methodSignatureForSelector:_cmd];
    NSInvocation      *invocation = [NSInvocation invocationWithMethodSignature:signature];

    [invocation setTarget:self];                    // index 0 (hidden)
    [invocation setSelector:_cmd];                  // index 1 (hidden)
    [invocation setArgument:&hello atIndex:2];      // index 2
    [invocation setArgument:&world atIndex:3];      // index 3

    // NSTimer's always retain invocation arguments due to their firing delay. Release will occur when the timer invalidates itself.
    [NSTimer scheduledTimerWithTimeInterval:1 invocation:invocation repeats:NO];
}
( NSInvocation setArgument atIndex example )
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;
}