views:

181

answers:

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 :(

A: 

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
EXC_BAD_ACCESS GDB error :'{
RealHIFIDude
Like I said, this may not work for your specific case. How are you getting your Method struct?
Dave DeLong