来自现有共享委托的覆盖/混合方法

时间:2009-08-10 15:52:32

标签: objective-c methods delegates swizzling

是否可以从现有代表中覆盖仅限某些功能,而不是自己完全是代表?

我尝试用我的替换目标IMP,但没有用:'(

更多细节:


+[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:)];

不工作!我的方法没有被调用:(

1 个答案:

答案 0 :(得分:3)

您可能不应该直接操作Method结构。请改用运行时函数。你需要#import运行时头,但是有一个很好的方法叫做method_setImplementation。它的工作原理如下:

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

这可能不适用于您的特定情况,因为class_getInstanceMethod可能不会为采用的协议定义的方法返回Method,但这是调整方法IMP的“正确”方法。