iOS Development Runtime Learning II: Runtime Exchange method

Source: Internet
Author: User
Tags uikit

#import "ViewController.h"/*Runtime (Exchange method): mainly want to modify the system to achieve the requirements of the method: for example, there is a project, has been developed for 2 years, suddenly the project owner added a feature, each time uiimage load the picture, tell me whether to load successfully when the system provides control can not meet my Our needs, we can 1: by inheriting system controls, overriding the system's methods to extend the behavior of subclasses (super calls three cases) 2: When you need to extend other properties or methods for a system class, which class is related, which class to create the classification for. 3: Using runtime to modify the class of the system, add properties, Exchange methods, message mechanism, dynamic increase method solution: 1: The method of rewriting the system: The new class inherits the system's class, overrides the system's method (if overwriting the behavior of the parent class does not need to call super, or under the Super method call: After preserving the original behavior of the parent class super, expand the subclass's own behavior, code written on super, you can modify super to pass parameters, such as rewrite Setframe, if you want to preserve the behavior of the parent class do not forget to call super.     Cons: Need to introduce header file in each Class 2: Write classification: for which system class to expand the properties and methods for which class to write classification 3: the implementation of the runtime to modify or access the system's class: Add attributes, Exchange methods, message mechanism, dynamic increase method     3: The need to use Runtime: do not need to import the header file, call or the System class original method, but the use of the runtime Exchange method. To add functionality to the system's imagenamed, you can only use Runtime (interactive method) 1. Add a category to the system's methods 2. Implement a method with extended functionality 3. Interactive method, only one interaction, 1. Custom UIImage 2.UI Image Add Category*/@interfaceViewcontroller ()@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //imagenamed = xmg_imagenamed Interaction These two methods implementUIImage *image = [UIImage imagenamed:@"1.png"]; }@end
#import "uiimage+image.h"#import<objc/message.h>/** Summary: 1: + (void) The difference between load and + (void) Initialize: + (void) load: Called when the class is loaded into memory, and regardless of whether there are no subclasses, it is called only once, before the main function, and uses: 1: You can create a new class in the class Now some configuration information 2:runtime the Exchange method, because only need to exchange the method, all can implement the interchange method in this method of code, used to implement only one time code 2:+ (void) Initialize: When the class is initialized to call, may be called multiple times, If there is no subclass, it will only be called once, if there is a subclass, the method will be called multiple times, if the subclass of the inheritance relationship, first call the parent class's + (void) Initialize method, and then to call the subclass of the + (void) Initialize method (if the inheritance relationship, Call a method, the first will go to the parent class to find, if the parent class does not have the implementation of the method to find the subclass to look for) Purpose: 1: In the navigation bar to set the global background, only need to set once, you can override the method settings, preferably in the method to determine the subclass, if you, the implementation of the global navigation If not yourself, skip the implementation. 2: In the creation of database code, can be created in this method, to ensure that only one database instance is initialized, you can also use dispatch or lazy loading method to initialize the database instance, but also to ensure that only one database instance is initialized. It is also possible to use dispatch in the + (void) Initialize method to ensure that even subclasses are initialized only once. 2: Exchange method: 1: Gets the method of a class: Class_getclassmethod: The first argument: the method to get which class  Second parameter: SEL: Which method is obtained Imagenamedmethod = Class_getclassmethod (self, @selector (imagenamed:));  Interactive method: Runtime Method_exchangeimplementations (Imagenamedmethod, Xmg_imagenamedmethod); That is, the external call xmg_imagenamed is equivalent to call the imagenamed, call imagenamed is equivalent to call Xmg_imagenamed 3: In the classification, it is best not to rewrite the system method, once rewritten, the system method implementation to kill, Because the classification does not inherit the parent class, but rather inherits the method of Nsobject,super without class, it directly overridesDropped the behavior of the parent class   */@implementationUIImage (Image)//when the class is loaded into memory, it is called only once .+ (void) load{//Self- UIImage//Get imagenamed//gets the method of which class//SEL: Which method to getMethod Imagenamedmethod =Class_getclassmethod (Self, @selector (imagenamed:)); //Get xmg_imagenamedMethod Xmg_imagenamedmethod =Class_getclassmethod (Self, @selector (xmg_imagenamed:)); //interaction method: Runtimemethod_exchangeimplementations (Imagenamedmethod, Xmg_imagenamedmethod); //Call imagenamed = Xmg_imagenamedmethod//Call Xmg_imagenamedmethod = imagenamed}//will be called multiple times//+ (void) Initialize//{//static dispatch_once_t Oncetoken;//dispatch_once (&oncetoken, ^{//        //    });//    //}//in the classification, it is best not to rewrite the system method, once rewritten, the system method implementation to kill//+ (UIImage *) imagenamed: (NSString *) name//{//    //Super--- parent class NSObject////}//1. Loading pictures//2. Determine if the load was successful+ (UIImage *) xmg_imagenamed: (NSString *) name{//ImageUIImage *image =[UIImage Xmg_imagenamed:name]; if(image) {NSLog (@"Load succeeded"); } Else{NSLog (@"Load Failed"); }        returnimage;}@end

The runtime implementation principle:

Second: Through inheritance rewrite implementation: Every time you need to import the header file, and many parts of the project need to be modified

#import <UIKit/UIKit.h>@interface  xmgimage:uiimage@end
#import "XMGImage.h"@implementationXmgimage//overriding method: You want to add extra functionality to the system's methods+ (UIImage *) imagenamed: (NSString *) name{//Real load Picture: Call Super to initialize a pictureUIImage *image =[Super Imagenamed:name]; if(image) {NSLog (@"Load succeeded"); } Else{NSLog (@"Load Failed"); }        returnimage; }@end

* development of the use of the scene: The system comes with the method is not enough, to the system's own method to extend some functions, and maintain the original function.

* Way One: Inherit the class of the system, overriding the method.

* mode two: Use runtime, Exchange method.

```

@implementation Viewcontroller

-(void) Viewdidload {

[Super Viewdidload];

Additional setup after loading the view, typically from a nib.

Requirements: To provide functionality to the Imagenamed method, each time the picture is loaded to determine whether the tablet is loaded successfully.

Step one: First make a classification, define a can load the picture and can print method + (Instancetype) Imagewithname: (NSString *) name;

Step two: Exchange imagenamed and Imagewithname implementation, you can call Imagewithname, indirectly invoke the implementation of Imagewithname.

UIImage *image = [UIImage imagenamed:@ "123"];

}

@end

@implementation UIImage (Image)

Called when the class is loaded into memory

+ (void) load

{

Exchange method

Get Imagewithname Method Address

Method imagewithname = Class_getclassmethod (self, @selector (imagewithname:));

Get Imagewithname Method Address

Method imageName = Class_getclassmethod (self, @selector (imagenamed:));

Interchange method address, equivalent to interchange implementation mode

Method_exchangeimplementations (Imagewithname, imageName);

}

The system method imagenamed cannot be overridden in the taxonomy because the system's functionality is overwritten and the super is not called in the classification.

can load pictures and print

+ (Instancetype) Imagewithname: (NSString *) name

{

This calls Imagewithname, which is equivalent to calling ImageName

UIImage *image = [self imagewithname:name];

if (image = = nil) {

NSLog (@ "Load empty picture");

}

return image;

}

@end

```

iOS Development Runtime Learning II: Runtime Exchange 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.