Hook Objective-C method

Source: Internet
Author: User

In Windows, there are two main types of hooks: Message hooks and function hooks. Sometimes you must use hooks when implementing some functions.

The function hook is mainly used to replace the entry address. In a broad sense, many things are hooks, such as the interrupt vector table.

It is possible to hook static and virtual functions in C ++, but it is difficult to hook common functions mainly because C ++ does not have a unified ABI standard.

However, you can use Objective-C hooks, and OC provides some runtime methods to make them relatively simple. For example, you do not need to use assembler to change the address.

The following uses the loadRequest: hook sub for UIWebView as an example to illustrate how to use the hook sub in Objective-C.

Class Name: UIWebView

Method Name: loadRequest:

Corresponding C prototype:

Typedef void (* UIWebView_loadRequest _ IMP) (UIWebView * self, SEL _ cmd, NSURLRequest * request );

Static UIWebView_loadRequest _ IMP original_UIWebView_loadRequest;

Void replaced_UIWebView_loadRequest (UIWebView * self, SEL _ cmd, NSURLRequest * request ){

Original_UIWebView_loadRequest (self, _ cmd, request );

// TODO:

}

// Add the following code to a vertex, such as application: didfinishlaunchingwitexceptions: to complete the hook.

Method method = class_getInstanceMethod (NSClassFromString (@ "UIWebView"), @ selector (loadRequest :));

Original_UIWebView_loadRequest = method_setImplementation (method, replaced_UIWebView_loadRequest );

Application scenarios:

Let's think about it. ^_^

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.