Go to the first, previous, next, last section, table of contents.


Features of the NSInvocation class

The ability to dynamically construct method invocations is an important feature in Objective-C libraries. This ability is used by various applications like distributed objects and various language interpreters to provide interface with the native methods or functions. In libFoundation the NSInvocation class is designed to provide this important facility.

In the OpenStep specification and some OpenStep Foundation implementations, the NSInvocation class is only used to encapsulate the arguments and return value of a forwarded message and to allow sending a different message in the context of the forwarding. The normal usage of the NSInvocation is in the -forwardInvocation: method:

- (void)forwardInvocation:(NSInvocation*)anInvocation
{
    [anInvocation setTarget:anotherObject];
    [anInvocation setSelector:anotherSelector];
    [anInvocation invoke];
}

In this example the NSInvocation object is created automatically by the Foundation library, with the help of the Objective-C runtime library, when a message is sent to an object that does not implement it. The actual implementation assumes the stack frame for the arguments of the method already exists (1). All the further changes to the method's arguments using the NSInvocation's methods are performed on that stack frame. After the method invocation returns you can access the return value and possibly change it, using the getReturnValue: and setReturnValue: methods.

The situation is different when you build a dynamic method invocation.

    BOOL flag = YES;
    int anInt = 1234;
    float aFloat = 12345.0;
    double aDouble = 98765.0;
    id invocation = [[NSInvocation new] autorelease];

    [invocation setSelector:
                @selector(setFlag:intValue:floatValue:doubleValue:)];
    [invocation setTarget:object];
    [invocation setArgument:&flag atIndex:2];
    [invocation setArgument:&anInt atIndex:3];
    [invocation setArgument:&aFloat atIndex:4];
    [invocation setArgument:&aDouble atIndex:5];
    [invocation invoke];

In this example the dynamic method invocation is constructed from scratch, by providing the object, the message selector and the arguments of the message. Then you can invoke the message and, after the message returns, you can access the return value.

It is very important to set the target and selector before setting the arguments. The NSInvocation is not otherwise able to construct the stack and registers frame and set the arguments of the method invocation.


Go to the first, previous, next, last section, table of contents.