実行時にプロトコルを追加する方法
Protocol *aProtocol = objc_allocateProtocol("TestingRuntimeDelegate");
AppDelegate *appInstance = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSLog(@"conformed Protocol ..%d",class_conformsToProtocol([self.delegate class], aProtocol));
protocol_addMethodDescription(aProtocol, @selector(itIsTestDelegate), "test", NO, NO);
objc_registerProtocol(aProtocol);
class_addProtocol([appInstance class], aProtocol);
//NSLog(@"adding Protocol %d",class_addProtocol([appInstance class], aProtocol));
if ([self.delegate conformsToProtocol:@protocol(TestDelegate)])
{
NSLog(@"conformed Protocol ..");
}
else
{
NSLog(@"conformed Protocol ..%d",class_conformsToProtocol([appInstance class], aProtocol));
class_conformsToProtocol([self.delegate class], aProtocol);
[appInstance performSelector:@selector(itIsTestDelegate)];
}
ただし、デリゲートメソッドはそのクラスで事前に定義されている必要があります。そうしないと、認識されないセレクターが原因でクラッシュします。
または、実行時にメソッドを追加することもできます。そうすれば、正常に機能します。
ただし、最初に次のファイルをインポートする必要があります。
#include <objc/runtime.h>