IOS method mixed write (swizzling .)

Source: Internet
Author: User

IOS method mixed write (swizzling .)

Swizzling in OC refers to the transparent replacement of one method with another. Simply put, it is to replace the method at runtime. Mixed write can be used to change the behavior of objects without source code (including system objects.

The mixed method code looks relatively intuitive. For example, the swizzling method is useful for local translation. Directly go to the swizze method awakeFromNib and replace it with your own method implementation to implement local translation. For details, refer to this article: IOS Localization Application.

The code used mainly includes the following 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 {// localized operation .... // Call the original awakeFromNib method [self localizeNibObject]; // this actually callthe original awakeFromNib (and not localizeNibObject) because we did some method swizzling}

Today, I ran back to github and looked at the open-source AGi18n project. The author converted all the original code into a classification implementation, which looks more intuitive. In the same way, swizzling is also used.

 

For example, NSobject + AGi18n classification code:

 

#import NSObject+AGi18n.h#import 
 
  @implementation NSObject (AGi18n)//By default do nothing when 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 exchanges the implementation of the awakeFromNib and awakeFromNibCustom methods, and runs the program as soon as it is started. This class is NSObject classification, and all controls inherit NSObject. In this way, the localization operation only needs to overwrite the localizeFromNib method in the control category to be localized. Taking UIButton as an example, localization 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 IOS 7 Programming: Pushing the Limits, a method-mixing example is used to print logs when an observer is added to the nsicationicationcenter. By comparing the two examples above and below, AGi18n still lacks some consideration in 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 let's take a look at the details. First, pass a selector and a function pointer (IMP) to this method ). We need to replace the current implementation of this method with the new implementation, and return the pointer of the old implementation for future calls. Three situations need to be considered: the class may directly implement this method, the method may be implemented by a parent class in the class hierarchy, or the method is not implemented at all. If the class or a parent class implements this method, calling class_getInstanceMethod will return an IMP; otherwise, NULL is returned.

 

If the method is not implemented at all, or a parent class is implemented, you need to use class_addMethod to add a method, which is the same as the general override method. If class_addMethod fails, we will know that this class directly implements the mixed write method, then we will use method_setImplementation to replace the old implementation with the new implementation.

After the call is finished, the original IMP is returned, and how the caller uses the return value is its own business.

 

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.