4

我希望能够调配协议方法,例如textFieldDidBeginEditing:tableView:didSelectRowAtIndexPath:。如何才能做到这一点?

4

1 回答 1

11

首先:你需要很好的理由来混合方法。

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

您可以调配协议中声明的方法。但是您在符合协议的类中执行此操作,而不是在协议本身中。

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

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
         }         
      }
    }
}
于 2015-05-05T04:42:03.840 回答