我希望能够使用 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/