Theocacao
Leopard
Design Element
Comment on "Dynamic Objective-C with NSInvocation"
by Robin — Sep 19
Here's a complete example:


@interface CurrentDate: NSObject
{
}

- (NSString *) stringForDate: (NSDate *)date usingFormatter: (NSDateFormatter *)formatter;

@end


@implementation CurrentDate;

- (NSString *) stringForDate: (NSDate *)date usingFormatter: (NSDateFormatter *)formatter
{

// yes, this doesn't do anything interesting.
// just using it as a simple example

return [formatter stringFromDate: date];

}

@end



int main (int argc, char *argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSDateFormatter * dateFormat = [[NSDateFormatter alloc] initWithDateFormat:@"%b %d %Y" allowNaturalLanguage: NO];

CurrentDate * currentDateClassObject = [[CurrentDate alloc] init];
NSString * currentDate = [currentDateClassObject stringForDate: [NSDate date] usingFormatter: dateFormat];

NSLog(@"currentDate: %@", currentDate);


// get an Objective-C selector variable for the method

SEL mySelector;
mySelector = @selector(stringForDate:usingFormatter:);


// create a singature from the selector

NSMethodSignature * sig = nil;
sig = [[currentDateClassObject class] instanceMethodSignatureForSelector: mySelector];


// create an actual invocation object and set the target to currentDateClassObject

NSInvocation * myInvocation = nil;
myInvocation = [NSInvocation invocationWithMethodSignature: sig];
[myInvocation setTarget: currentDateClassObject];
[myInvocation setSelector: mySelector];


// add first argument

NSDate * myDate = [NSDate date];
[myInvocation setArgument: &myDate atIndex: 2];


// add second argument

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle: NSDateFormatterMediumStyle];
[myInvocation setArgument: &dateFormatter atIndex: 3];

NSString * result = nil;
[myInvocation retainArguments];
[myInvocation invoke];
[myInvocation getReturnValue: &result];

NSLog(@"The result is: %@", result);

[pool release];

return 0;

}
Back to "Dynamic Objective-C with NSInvocation"
Design Element

Copyright © Scott Stevenson 2004-2015