iOS black Magic-method swizzling

Source: Internet
Author: User

Company at the end of the new year before the release of a version, has been very busy, long time no update blog. Just now the new version of the development of almost, time to summarize.
Due to the recent development of new versions, it is not enough to cause crashes during development and debugging, and to induce crashes caused by previous bugs. And the project is also very difficult to troubleshoot, just think of the previous research method swizzling, consider whether you can use the Apple's "black magic" to solve the problem, of course, the use of this black magic is not limited to solve these problems ...

Demand

Take our company project, our company is to do the navigation, and the project size is large, the various controller functions have been realized. Suddenly one day the eldest brother came over, said we want to add statistics function on all pages, that is, users enter this page to count once. We will think of some of the following methods:

Manually add

Directly and simply rude in each controller to add statistics, copy, paste, copy, paste ...
The above method is too low, consumes time and is very difficult to maintain later, it will let the developers in the back scold dead.

Inherited

We can use one of the features of OOP and inherit the way to solve this problem. Create a base class, add a statistical method to the base class, and other classes inherit from the base class.

However, this modification is still very large, and the customization is poor. After a new person joins, it is not advisable to instruct them to inherit from this base class.

Category

We can build a category for Uiviewcontroller and then introduce this category in all controllers. Of course we can also add a PCH file and add the category to the PCH file.

We create a category to override the system approach, and the system invokes the code in the category first, and then calls the code in the original class.

We can look at the following pseudo-code:

123456 #import "UIViewController+EventGather.h"@implementation UIViewController (EventGather)- (void)viewDidLoad {   NSLog(@"页面统计:%@", self);}@end

Method swizzling

We can use Apple's "black Magic" Method Swizzling,method swizzling is essentially an exchange of IMP and SEL.

Method swizzling Principle

Method swizzing occurs at run time and is mainly used to exchange two method at run time, we can write the method swizzling code anywhere, but only in this method After the swilzzling code is executed, the interchange does not work.

And method Swizzling is also an implementation of AOP (facet slicing programming) in iOS, and we can use this feature to implement AOP programming.

First, let's take a look at two images to see how the method swizzling is implemented.

Figure A

Figure II

In Figure one above Selector2 originally corresponds to IMP2, but in order to more easily achieve specific business needs, we added Selector3 and IMP3 in Figure two, and Selector2 point to IMP3, and Selector3 point to IMP2, so that the implementation of the "Method Interchange".

In the runtime feature of the OC language, the method of invoking an object is to send a message to the object. is to find the corresponding SEL from the list of methods by looking up a list of methods that receive the message object, which corresponds to a imp (an IMP can correspond to multiple sel), and the Imp finds the corresponding method call.

There is a dispatch table in each class, and this dispatch table essentially corresponds to the SEL in the class and the IMP (which can be understood as a function pointer). And our method swizzling is to manipulate this table to have the SEL correspond to another imp.

Method swizzling Use

When implementing method Swizzling, the core code is basically a runtime C-language API:

12 OBJC_EXPORT void method_exchangeImplementations(Method m1, Method m2)  __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

Implementation ideas

Take the above-mentioned page statistics requirements, this requirement in many companies are very common, our following demo through method swizzling simple implementation of this requirement.

Let's add a category to Uiviewcontroller and then add method swizzling to the + (void) Load method in the category, and the method we use to replace it is also written in this category. Because the load class method is a method that the class is loaded into memory when the program is running, it executes earlier and does not require us to call it manually. And this method is unique, that is, it will only be called once, do not worry about the problem of resource looting.

When defining method swizzling in our custom approach, we need to be careful to prefix as much as possible to prevent naming conflicts with other places, and the method swizzling name must be unique, at least in the class that is replaced.

12345678910111213141516171819202122232425262728 #import "UIViewController+swizzling.h"#import @implementation UIViewController (swizzling)+ (void)load {    [superload];    // 通过class_getInstanceMethod()函数从当前对象中的method list获取method结构体,如果是类方法就使用class_getClassMethod()函数获取。    Method fromMethod = class_getInstanceMethod([self class], @selector(viewDidLoad));    Method toMethod = class_getInstanceMethod([self class], @selector(swizzlingViewDidLoad));    /**     *  我们在这里使用class_addMethod()函数对Method Swizzling做了一层验证,如果self没有实现被交换的方法,会导致失败。     *  而且self没有交换的方法实现,但是父类有这个方法,这样就会调用父类的方法,结果就不是我们想要的结果了。     *  所以我们在这里通过class_addMethod()的验证,如果self实现了这个方法,class_addMethod()函数将会返回NO,我们就可以对其进行交换了。     */    if(!class_addMethod([self class], @selector(viewDidLoad), method_getImplementation(toMethod), method_getTypeEncoding(toMethod))) {        method_exchangeImplementations(fromMethod, toMethod);    }}// 我们自己实现的方法,也就是和self的viewDidLoad方法进行交换的方法。- (void)swizzlingViewDidLoad {    NSString *str = [NSString stringWithFormat:@"%@", self.class];    // 我们在这里加一个判断,将系统的UIViewController的对象剔除掉    if(![str containsString:@"UI"]){        NSLog(@"统计打点 : %@", self.class);    }    [self swizzlingViewDidLoad];}@end

See the above code, certain people will ask: Lou Zhu, you are too careless, you in the Swizzlingviewdidload method and called the [self swizzlingviewdidload], this does not produce a recursive call it?

Answer: however .... and will not????。

Remember that picture and figure two above us? The implementation principle of method swizzling can be understood as "methods interchange". Suppose we swap A and B two methods to send a message to the A method when the B method is executed, and the A method is executed when the message is sent to the B method.

For example, the code above, when the system calls Uiviewcontroller's Viewdidload method, actually executes the Swizzlingviewdidload method we implement. When we call [self swizzlingviewdidload] inside the Swizzlingviewdidload method, the Viewdidload method of Uiviewcontroller is executed.

Method swizzling class Cluster

I also said that in our project development process, often because of the nsarray array out of bounds or nsdictionary key or value of nil and other problems caused by the crash, for these problems Apple will not report a warning, but directly crash, feel that Apple is really a bit "too tough ”。

Thus, we can according to the above study, to Nsarray, Nsmutablearray, Nsdictionary, Nsmutabledictionary and other classes of method swizzling, the implementation of the way or according to the above example. But.... You find that method swizzling does not work at all, the code is not written wrong Ah, what the hell is it?

This is because method swizzling does not work for nsarray of these clusters. Because these class cluster classes, is actually an abstract factory design pattern. There are many other subclasses within the abstract factory that inherit from the current class, and the abstract factory class will create different abstract objects to use depending on the situation. For example, we call Nsarray's Objectatindex: method, which is judged internally by the method, creating a different abstract class inside the operation.

So that's what we're doing with the Nsarray class, just manipulating the parent class, creating other subclasses inside Nsarray to perform the operation, not nsarray itself, so we should do the "real".

Below we implemented a crash that prevented Nsarray from calling the Objectatindex: method, removing the array from the subscript when it was crossed:

12345678910111213141516171819202122232425262728 #import "NSArray+LXZArray.h"#import "objc/runtime.h"@implementation NSArray (LXZArray)+ (void)load {    [superload];    Method fromMethod = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:));    Method toMethod = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(lxz_objectAtIndex:));    method_exchangeImplementations(fromMethod, toMethod);}- (id)lxz_objectAtIndex:(NSUInteger)index {    if(self.count-1 < index) {        // 这里做一下异常处理,不然都不知道出错了。        @try{            return[self lxz_objectAtIndex:index];        }        @catch(NSException *exception) {            // 在崩溃后会打印崩溃信息,方便我们调试。            NSLog(@"---------- %s Crash Because Method %s  ----------\n", class_getName(self.class), __func__);            NSLog(@"%@", [exception callStackSymbols]);            returnnil;    }        @finally {}    } else{        return[self lxz_objectAtIndex:index];    }}@end

Everybody found out, __nsarrayi is Nsarray real class, and Nsmutablearray is not the same????。 We can get the real class through the runtime function:

1 objc_getClass("__NSArrayI")

Below we list some of the commonly used clusters of "the Flesh":

Method swizzling Package

In the project we will definitely use method swizzling in many places, and there are a lot of things to be aware of when using this feature. We can encapsulate the method swizzling, or we can use some more mature third parties.
Here I recommend a third-party-jrswizzle with the most stars on GitHub

Inside the core is two classes, the code looks very refreshing.

12345678 #import @interface NSObject (JRSwizzle)+ (BOOL)jr_swizzleMethod:(SEL)origSel_ withMethod:(SEL)altSel_ error:(NSError**)error_;+ (BOOL)jr_swizzleClassMethod:(SEL)origSel_ withClassMethod:(SEL)altSel_ error:(NSError**)error_;@end// MethodSwizzle类#import BOOL ClassMethodSwizzle(Class klass, SEL origSel, SEL altSel);BOOL MethodSwizzle(Class klass, SEL origSel, SEL altSel);

is Method swizzling dangerous?

Since method swizzling can manipulate this class's dispatch table, the result of the operation will have an effect on all current classes and subclasses, so some people think that method swizzling is a dangerous technique, It can easily lead to unforeseen bugs, which are often very difficult to find and debug.
This question can be quoted in the words of the Great God: Using Method swizzling programming is like cutting vegetables using a sharp knife, some people worry about cutting to their own so afraid of sharp knives, but in fact, the use of blunt knife is often more prone to accidents, and the knife is more safe.

iOS black Magic-method 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.