动态创建的方法未被调用

时间:2016-04-19 22:27:22

标签: ios objective-c runtime

使用来自另一个类的false在AppDelegate中动态创建方法后,它永远不会被调用。

我在运行时创建的方法是:

class_addMethod

我用来动态创建上一个方法的代码是:

-(BOOL)application:(UIApplication *)application
           openURL:(NSURL *)url {
  //Do something...
  return YES;
} 

与我的 { UIApplication* app = [[UIApplication sharedApplication] delegate]; class_addMethod([app class], @selector(application:openURL:), (IMP)myMethodIMP, @"B@:"); } 功能一起:

IMP

我已经确认使用 bool myMethodIMP(id self, SEL _cmd, UIApplication *application, NSURL *url) { [self application: application openURL:url]; //Do something... return YES; } 方法

确实在我的应用代理上创建了它

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

@bbum你是对的,UIApplication缓存代理人没有响应该方法,所以你可以这样做

@interface UIApplication (MBShare)

@end

@implementation UIApplication (MBShare)

+ (void) load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        SEL originalSelector = @selector(setDelegate:);
        SEL swizzledSelector = @selector(mb_setDelegate:);

        Method originalMethod = class_getInstanceMethod(self, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);

        BOOL didAddMethod =
        class_addMethod(self,
                        originalSelector,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));

        if (didAddMethod) {
            class_replaceMethod(self,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }

    });
}

- (void) mb_setDelegate: (id) delegate
{
    //hook method here
    [[MBShareApi shareInstance] hookAppDelegate: delegate];
    [self mb_setDelegate: delegate];
}

@end

更多细节请参阅:https://github.com/Baoge2012/MBShare/blob/master/MBShare/MBShareApi.m