【问题标题】:Overriding / Swizzling methods from an existing shared delegate来自现有共享委托的覆盖/调配方法
【发布时间】:2010-11-18 08:21:54
【问题描述】:

是否可以仅覆盖现有委托的某些功能,而我们自己不完全是委托?

我尝试用我的替换目标 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:)];

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

【问题讨论】:

  • 我看到你想出了如何提问。为什么不赢得徽章并返回并删除您对 TAOCP 问题的“未回答”?
  • 我对问题进行了编辑、重新命名和重新标记。最好保持标题简短并在问题中进行解释。另外,让标签对问题进行分类,而不是将 [OBJ-C] 作为标题前缀等。

标签: objective-c methods delegates swizzling


【解决方案1】:

您可能不应该直接操作 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,但这是调配 Method IMP 的“正确”方式。

【讨论】:

  • 就像我说的,这可能不适用于您的具体情况。你是如何得到你的 Method 结构的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 2014-08-18
相关资源
最近更新 更多