1

Is it possible to override ONLY CERTAIN functions from an exisiting delegate, without ourself being a delegate totally?

I tried replacing the target IMP with mine, didn't work :'(

More detail:


+[SomeClass sharedDelegate]

-[sharedDelegate targetMethodToBeOverridden:Arg:] //OUR method needs to be called, not this

Method *targetMethod;  // targetMethodToBeOverridden identified by class_copymethodlist magic

targetMethod->method_imp =  [self methodForSelector:@selector(overriddenDelegateMethod:Arg:)];

NOT WORKING! My Method is not being called :(

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
RealHIFIDude
  • 71
  • 1
  • 2
  • 7
  • I see you figured out how to ask questions. Why not earn a badge and go back and delete your "non-answer" to the TAOCP question? – tvanfosson Aug 10 '09 at 15:58
  • I edited, retitled, and retagged the question. It's best to keep the title short and explain in the question. Also, let the tags classify the question, rather than putting **[OBJ-C]** as a title prefix, etc. – Quinn Taylor Aug 10 '09 at 16:12

1 Answers1

3

You probably shouldn't be manipulating the Method struct directly. Use the runtime function instead. You'll need to #import the runtime header, but there's a nice method in there called method_setImplementation. It'll work something like this:

id targetObject = [SomeClass sharedDelegate];
Method methodToModify = class_getInstanceMethod([targetObject class], @selector(replaceMe:argument:));
IMP newImplementation = [self methodForSelector:@selector(overriddenDelegateMethod:Arg:)];
method_setImplementation(methodToModify, newImplementation);

This may not work for your specific case, since class_getInstanceMethod might not return the Method for a method defined by an adopted protocol, but this is the "proper" way to swizzle Method IMPs.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498