Surrogate object / forwarding
Surrogate object / forwarding
- Subject: Surrogate object / forwarding
- From: "Sven A. Schmidt" <email@hidden>
- Date: Thu, 3 Jan 2002 14:01:29 +0100
I've come across the following while trying to "fake" a subclass of an
NSMutableDictionary. Because NSMutableDictionary is part of a class
cluster, I chose to build a composite class (i.e. an NSObject child that
includes a dictionary), and forward the NSMutableDictionary messages to
the included object.
To that end, I implemented the following methods ([ self dictionary ] is
(obviously) the accessor to the included dictionary):
- (void)forwardInvocation: (NSInvocation *)invocation {
if ( [[ self dictionary ] respondsToSelector: [invocation
selector] ] ) {
[ invocation invokeWithTarget: [ self dictionary ] ];
}
}
- (BOOL)respondsToSelector: (SEL)aSelector {
return [ super respondsToSelector: aSelector ] || [[ self
dictionary ] respondsToSelector: aSelector ];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
if ( [ super respondsToSelector: aSelector ] ) {
return [ super methodSignatureForSelector: aSelector ];
} else {
return [[ self dictionary ] methodSignatureForSelector: aSelector ];
}
}
----------------------------------------
While this works fine, I still have some issues/questions:
1. I get compiler warnings that my class doesn't respond to the
forwarded messages (they are actually forwarded at runtime). Is there a
way to tell the compiler that this isn't true?
2. My class adds new selectors (like setMin:). From looking at the
respondsToSelector: method above, I'm surprised that it still knows that
it responds to them. Is it because they're not public?
3. The NSObject class description has the following to say about
instancesRespondToSelector:
"+ (BOOL)instancesRespondToSelector:(SEL)aSelector
Returns YES if instances of the class are capable of responding to
aSelector messages, NO otherwise. To ask the class whether it, rather
than its instances, can respond to a particular message, send the
respondsToSelector: NSObject protocol instance method to the class
instead."
Now, why would I use a class method to find out about instance
responders, while the instance method respondsToSelector: (from its
description) seems to handle class and instance methods alike? I this a
doc error, i.e. should instancesRespondToSelector: inform about class
methods, not instance methods?
Puzzled and grateful for advice,
Sven