Runtime (ii): The black magic of the unconscious of the modified class method

Source: Internet
Author: User
Tags uikit

If we want to rewrite the method of a class, what methods do we take into account?

1. Classification: The main disadvantage of classification is that the classification is not a parent class and cannot call a method of the parent class. and need to introduce the header file, easy to be found.

2. Inheritance: Although inheritance can implement the method of overriding the parent class, the action is too large to be discovered by others.

3.runtime: Method Exchange! Although the classification is used, but! No need to introduce header file!!

Nonsense not much to say directly on the code

1. Write a classification for Uicolor and introduce #import <objc/message.h>

#import <UIKit/UIKit.h>@interface  uicolor (extension)+ (uicolor*) My_redcolor; @end
#import "Uicolor+extension.h"#import<objc/message.h>@implementationuicolor (extension)//This method will be called when the classification is loaded.+ (void) load{Method Redmethod= Class_getclassmethod ([uicolorclass], @selector (Redcolor)); Method Myredmethod= Class_getclassmethod ([uicolorclass], @selector (My_redcolor)); Method_exchangeimplementations (Redmethod, Myredmethod);}+ (Uicolor *) my_redcolor{NSLog (@"111111"); //1. Modify the modification method directly    return[Uicolor Graycolor]; //2. Call the previous method, it should be noted that this time [Uicolor My_redcolor] actually executed is: Redcolor this method. This time if using [Uicolor Redcolor] will cause a dead loop. //return [Uicolor Redcolor];}@end

2. There is no need for any introduction, so long as the [Uicolor Redcolor] is called in any class, the method Exchange is implemented.

For example: Controller Self.view.backgroundColor = [Uicolor Redcolor];

Runtime (ii): The black magic of the unconscious of the modified class method

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.