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?
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.