views:

59

answers:

1

I have the following two class:

//file FruitTree.h
@interface FruitTree : NSObject
{
   Fruit * f;
   Leaf * l;
}
@end

//file FruitTree.m
@implementation FruitTree
   //here I get the number of seeds from the object f
@end



//file Fruit
@interface Fruit : NSObject
{
    int seeds;
}
-(int) countfruitseeds;
@end

My question is at the point of how I request the number of seeds from f. I have two choices.

Either: Since I know f I can explicitly call it, i.e. I implement the method

-(int) countfruitseeds
{
    return [f countfruitseeds];
}

Or: I can just use forwardInvocation:

- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
// does the delegate respond to this selector?
if ([f respondsToSelector:selector])
    return [f methodSignatureForSelector:selector];
    else if ([l respondsToSelector:selector])
            return [l methodSignatureForSelector:selector];
    else
    return [super methodSignatureForSelector: selector];
}
- (void)forwardInvocation:(NSInvocation *)invocation
{   
[invocation invokeWithTarget:f];
}

(Note this is only a toy example to ask my question. My real classes have lots of methods, which is why I am asking.)

Which is the better/faster method?

+1  A: 

The direct method implementation is much, much faster. But if you want a real proxy object, the forwardInvocation: route is really the only way to go. Even if you us a macro to make the method declarations very short, you'd still need to write all the method names you wanted and keep the list up to date when any are added or removed.

Chuck
do you have a good reference?
John Smith
A direct reference for what? The fact that sending a single message is faster than wrapping the call in an NSInvocation object and then sending several more messages? Here's a good refernce: http://www.mikeash.com/pyblog/performance-comparisons-of-common-operations.html (NSInvocation comes out 160 times slower than a normal message send, and that's not counting the cost of creating the invocation AFAICT)
Chuck