ios - 协议(protocol)的方法调配

标签 ios objective-c uikit method-swizzling

我希望能够使用 Swizzle 协议(protocol)方法,例如 textFieldDidBeginEditing:tableView:didSelectRowAtIndexPath:。 如何做到这一点?

最佳答案

首先:调配方法需要非常充分的理由。

没有“协议(protocol)的方法调配”。方法调配意味着您将方法实现指针交换为选择器。协议(protocol)没有实现。

您可以调配协议(protocol)中声明的方法。但是你是在符合协议(protocol)的类中做的,而不是在协议(protocol)本身。

这是一个查找实现方法的类的示例:

SEL selector = …;      // The selector for the method you want to swizzle
IMP code = …;          // The implementation you want to set
Protocol *protocol = …; // The protocol containing the method

// Get the class list
int classesCount = objc_getClassList ( NULL, 0 );
Class *classes = malloc( classCount * sizeof(Class));
objc_getClassList( classes, classesCount );

// For every class 
for( int classIndex = 0; classIndex < classesCount; classIndex++ )
{
    Class class = classes[classIndex];

    // Check, whether the class implements the protocol
    // The protocol confirmation can be found in a super class
    Class conformingClass = class;
    while(conformingClass!=Nil)
    {
      if (class_conformsToProtocol( conformingClass, protocol )
      {
        break;
      }
      conformingClass = class_getSuperclass( conformingClass );
    }

    // Check, whether the protocol is found in the class or a superclass
    if (conformingClass != Nil )
    {
      // Check, whether the protocol's method is implemented in the class,
      // but NOT the superclass, because you have to swizzle it there. Otherwise
      // it would be swizzled more than one time.
      unsigned int methodsCount;
      Method *methods = class_copyMethodList( class, &methodsCount );

      for( unsigned methodIndex; methodIndex < methodsCount; methodIndex++ )
      {
         if (selector == method_getName( methods[methodIndex] ))
         {
            // Do the method swizzling
         }         
      }
    }
}

关于ios - 协议(protocol)的方法调配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30044366/

相关文章:

objective-c - 对当前线程调用堆栈上的对象调用release

ios - swift 5 : index out of range when returning the array count from tableView numberOfRowsInSection

ios - Swift Cocoa 按钮未到位

安装解析通知后 iOS 应用程序无法离线工作 - xcode

objective-c - Objective-C中的变量声明差异

ios - 强引用dispatch_queue的retain cycle

ios - UITableViewCell 外观不改变 textLabel 字体

ios - 以编程方式修改约束 Swift

ios - 屏幕上显示的应用内购买价格(带货币)

ios - UISegmentedControl 的 NSAttributedstring