iOS Black Magic Method swizzling

Source: Internet
Author: User

This black magic should belong to OC, it is based on runtime implementation of bogus DAFA.

So what is method swizzling? From the literal point of view is called the method of coordination, probably this means. Use this magic to replace an existing method with a custom method, a bogus, a rescue.

Using the method is simple, the code is basically the following framework. But it has a strong magic, this is a way to hook ah.

/** * Method swizzling * Black magic Bogus * * #import "uiviewcontroller+extension.h" #import <objc/runtime.h>@ Implementation Uiviewcontroller (Extension)//In order to ensure certain execution put the code into + (void) load; + (void) load {[Super load]; //thread safe    Perform only one static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{//Get class class = [Self class];//class class = Object_getcla        SS ((ID) self);        Package selector SEL originalselector = @selector (viewwillappear:);        SEL swizzledselector = @selector (lw_viewwillappear:);        Encapsulation Method Originalmethod = Class_getinstancemethod (class, Originalselector);        Method Swizzledmethod = Class_getinstancemethod (class, Swizzledselector); Add method BOOL Methoddidadd = Class_addmethod (class, Originalselector, Method_getimplementation (Swizzledmethod), meth        Od_gettypeencoding (Swizzledmethod)); if (Methoddidadd) {//Replace method Class_replacemethod (class, Originalselector, MethoD_getimplementation (Swizzledmethod), method_gettypeencoding (Swizzledmethod));        }else {//Exchange method Method_exchangeimplementations (Originalmethod, Swizzledmethod); }    });}    #pragma mark-Custom Magic Method-(void) Lw_viewwillappear: (BOOL) animated {[Self lw_viewwillappear:animated]; NSLog (@ "BLack Magic");}

Attention:

1 + (void) load;

2 dispatch_once;

3 [self lw_viewwillappear:animated]; Do not return to the dead loop if [self viewwillappear:animated];

iOS Black Magic Method swizzling

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.