1

I want to Hook delegate(protocol) method in iOS, who can tell me how to do it?

such as hook method applicationDidFinishLaunching:

I do it like this, but it is not work...

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); 
j0k
  • 22,600
  • 28
  • 79
  • 90
ataraxia
  • 23
  • 3

2 Answers2

0

applicationDidFinishLaunching is a method implemented by the application DELEGATE, not UIApplication itself. There is absolutely no reason why you would need to swizzle methods on UIApplication. Just implement these methods in your delegate.

For cases where you want to override a method in a class provided by Apple you can do so by creating a category on them. The added category method will override the system method by the same method signature.

Cocoanetics
  • 8,171
  • 2
  • 30
  • 57
  • Even though old question, why don't you see any reason to swizzle `UIApplicationDelegate` methods? – atxe Sep 12 '14 at 13:45
0

you shound exchange the method of the class who implemented the protocol.like this:

    // 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");
  • 1
    why "Like this??" A good answer will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO. Please add some description to make others understand. – Rucha Bhatt Joshi Sep 05 '17 at 06:56