textFieldDidBeginEditing:
やのようなプロトコル メソッドを Swizzle できるようにしたいtableView:didSelectRowAtIndexPath:
。これはどのように行うことができますか?
2021 次
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 に答える