1

我想在 iOS 中挂钩委托(协议)方法,谁能告诉我怎么做?

比如钩子法applicationDidFinishLaunching:

我这样做,但它不工作......

extern IMP original_UIApplication_applicationDidFinishLaunching;
extern void replaced_UIApplication_applicationDidFinishLaunching(UIApplication<UIApplicationDelegate> * self, SEL cmd, UIApplication* application); 

MSHookMessageEx(objc_getMetaClass("UIApplication"),
                @selector(applicationDidFinishLaunching:), 
                (IMP)replaced_UIApplication_applicationDidFinishLaunching, 
                (IMP *)&original_UIApplication_applicationDidFinishLaunching); 
4

2 回答 2

0

applicationDidFinishLaunching 是由应用程序 DELEGATE 实现的方法,而不是 UIApplication 本身。绝对没有理由需要在 UIApplication 上调配方法。只需在您的委托中实现这些方法。

对于您想要覆盖 Apple 提供的类中的方法的情况,您可以通过在它们上创建一个类别来实现。添加的类别方法将通过相同的方法签名覆盖系统方法。

于 2012-12-10T09:08:41.893 回答
0

你应该交换实现协议的类的方法。像这样:

    // Protocol Method Exchange
    int numClasses = objc_getClassList(NULL, 0);

    Class *list = (Class *)malloc(sizeof(Class) * numClasses);
    objc_getClassList(list, numClasses);
    for (int i = 0; i < numClasses; i++) {
        if (class_conformsToProtocol(list[i], @protocol(TowstViewDelegate)) &&
            class_getInstanceMethod(list[i], @selector(submit))) {
            NSLog(@"%@ sumit have exchanged",NSStringFromClass(list[i]));
            jm_swizzleSelector(list[i], @selector(submit), @selector(hk_submit));
        }
    }
    free(list);
    NSLog(@"Exchange END");
于 2017-09-05T06:35:16.970 回答