iOS method Mix (swizzling.)

Source: Internet
Author: User

The swizzling in OC refers to transparently replacing one method with another. The simplest is to replace the method at run time. Using method blending can change the behavior of objects that do not have source code, including system objects.

The method of mixed-write code looks relatively straightforward, for example, before the localization of the translation is useful to the Swizzling method. Go directly to the Swizze method awakefromnib and then replace it with your own method implementation to achieve localized translation. You can read this article in more detail: iOS localization app.

The main use of the code is also the two sentences:

+ (void) load  {      //autoload:swizzle-awakefromnib With-localizenibobject as soon as the app (and thus this class) is loaded      Method localizenibobject = Class_getinstancemethod ([NSObject class], @selector (Localizenibobject));      Method awakefromnib = Class_getinstancemethod ([NSObject class], @selector (awakefromnib));      Method_exchangeimplementations (awakefromnib, localizenibobject);  
-(void) Localizenibobject  {        //localization operation ....    Call the original awakefromnib method      [self localizenibobject];//This actually calls the original awakefromnib (a nd not localizenibobject) because we do some method swizzling  

Today I ran back to GitHub to see the agi18n this open source project, the author of the original code is all replaced by the classification to achieve, it seems more intuitive, when the same is also achieved through swizzling.

such as NSObject + agi18n classification code:

#import "Nsobject+agi18n.h" #import <objc/runtime.h> @implementation nsobject (agi18n)//by default do Nothing localizing-(void) localizefromnib {} #pragma mark-method swizzling+ (void) load {    Method awakefromniboriginal = Class _getinstancemethod (Self, @selector (awakefromnib));    Method Awakefromnibcustom = Class_getinstancemethod (self, @selector (awakefromnibcustom));            Swizzle methods    method_exchangeimplementations (awakefromniboriginal, awakefromnibcustom);} -(void) Awakefromnibcustom {    //call standard methods    [self awakefromnibcustom];        Localize    [self localizefromnib];} @end

The above code swaps the implementation of the awakefromnib and Awakefromnibcustom methods, which are executed when the program is started. Because this class is a nsobject classification, and all controls are inherited NSObject, the localization operation simply needs to rewrite the Localizefromnib method in the control classification that requires localization, and in UIButton, for example, the localization operation becomes very simple.

#import "Uibutton+agi18n.h" @implementation UIButton (agi18n)-(void) localizefromnib {    //replace text with Localizable version    Nsarray *states = @[@ (UIControlStateNormal), @ (uicontrolstatehighlighted), @ ( uicontrolstatedisabled), @ (uicontrolstateselected), @ (uicontrolstateapplication)];    For (NSNumber *state in states) {        NSString *title = [self titleForState:state.integerValue];        if (Title.length > 0) {            [self settitle:[[nsbundle mainbundle] localizedstringforkey:title value:@ "" Table:nil] ForState:state.integerValue];}}    } @end

-----------------------------------------------------------------------------------------------------Split Line----------------- ------------------------------------------------------------------------------------------------------------

In the book "IOS 7 programming:pushing The Limits", the method is mixed with an example of printing a log when adding an observer in Nsnotificationcenter. By comparing the above two examples, the agi18n is still missing in the swizzling.

@interface NSObject (rnswizzle) + (IMP) Swizzleselector: (SEL) origselector withimp: (imp) newimp; @end @implementation NSObject (Rnswizzle) + (IMP) Swizzleselector: (SEL) origselector withimp: (imp) newimp{    Class class = [self class];    Method Origmethod = Class_getinstancemethod (class, origselector);    IMP origimp = method_getimplementation (Origmethod);    if (!class_addmethod (self, origselector, Newimp, method_gettypeencoding (Origmethod))) {        Method_ Setimplementation (Origmethod, newimp);    }        return origimp;} @end
Next look at the details. This method is first passed a selector and a function pointer (IMP). What we want to do is replace the current implementation of the method with the new implementation and return the old implementation pointer for later invocation. There are 3 scenarios to consider: A class might implement this method directly, either by a parent class in the class hierarchy or by a method that is not implemented at all. If the class or a parent class implements this method, the call to Class_getinstancemethod returns an IMP, or NULL is returned.

If the method is not implemented at all, or is implemented by a parent class, then you need to add the method with Class_addmethod, which is the same as the usual override method. If Class_addmethod fails, we know that this class directly implements the method that is being mixed, then instead uses method_setimplementation to replace the old implementation with the new implementation.

Well, after returning the original IMP, how the caller uses the return value is its own thing.

Reference: "IOS 7 programming:pushing The Limits"

iOS method Mix (swizzling.)

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.