Method Swizzling, methodswizzling

Source: Internet
Author: User

Method Swizzling, methodswizzling

The article is from Xiao binlang's iOS blog. He has always thought that the blog UI of csdn is not very nice and he is not very good at reading blogs, so he set up a blog by himself. You are welcome to visit my blog at the link. You are also welcome to join the QQ Group to discuss iOS technology issues.

----------------


Time Flies, I haven't written a blog for a long Time. I 've been playing with the design pattern recently. The design pattern is a big stuff. I think it's not Time to write them out. Wait a while. I saw a fun little thing in the past few days and thought it was good. So I 'd like to share it with you.

Origin

I believe that all of you have used the NSMutableDictionary-setObject: forKey: method. When the object is nil, it will crash. Every time we write code, we need to judge nil, which is very troublesome. In addition, if you forget to judge nil, it is very likely that the bug will be released. Online apps often encounter such crashes.

In this case, I want to use a method instead of-setObject: forKey:. When obj is not nil,-setObject: forKey: Is used normally, and nil is used without any operation.

There are three solutions to change the implementation of a method: override, caregory, swizzling

1. Override

Rewriting is the most common way to change the implementation of a method. First, create a CustomDictionary that inherits from NSMutableDictionary and then override-setObject: forKey:. We use CustomDictionary when using it.

This can achieve the goal, but it is also very troublesome. First, we must create a new class that inherits from NSMutableDictionary and modify all the old code that uses NSMutableDictionary. If a new employee comes to the team, he must be told not to use NSMutableDictionary, but to use CustomDictionary ......

My god, this is too troublesome, pass ~

2. Category

Category is a great thing in OC. It is said that no other language exists. So let's see how to use category?
First, this method in category cannot be the same as-setObject: forKey:. Otherwise, we cannot call this-setObject: forKey: Of the system. Therefore, we name it-safeSetObject: forKey :, -setObject: forKey is rewritten in this method.

The proportion of this solution is better. At least we don't need to create a new class, and we can achieve our goal completely. However, for the modification of old code, it is still necessary to give a try to new people ......

In fact, we have a more perfect solution.

3. Swizzling

In iOS, Method Swizzling is not very common. Let's take a closer look at Method Swizzling.

A method is divided into two parts: Method Name and method implementation, that is, SEL and IMP. Generally, each method has a fixed SEL and IMP, which are inseparable.

Each class contains a list of methods that store the SEL ing between SEL and IMP (image source ):

Method Swizzling is to swap the SEL and IMP of the two methods (image source ):

Let the method of selectorC be called to execute the implementation of selectorN.

Next, let's take a look at what to do to implement Method Swizzling?
First, create an NSMutableDictionary category and write the method used to replace-setObject: forKey:

@ Implementation NSMutableDictionary (Override)-(void) overrideSetObject :( id) anObject forKey :( id <NSCopying>) aKey; {if (anObject) {/** note: you must call your own method name */[self overrideSetObject: anObject forKey: aKey] ;}}@ end

We are surprised to see this. In-overrideSetObject: forKey: The method actually calls its own method name. Isn't this an endless loop?

Don't forget, this method will Swizzling, that is, the name of the method called inside the method will point to the system implementation. If you don't understand it here, you can skip it. I will explain it to you in detail later.

The method is ready. Now we have Swizzling.

The first thing to note is that Swizzling must be performed before the method is executed. Otherwise, it will be meaningless if all the methods are executed. Next, you need to check whether you want to consider multithreading.

In general, the Swizzling code is put in the + load method, because the + load method is executed at startup (-application: didfinishlaunchingwitexceptions: before) and will definitely be used before. And multithreading is not required.

+ (Void) load {/** get SEL and Method */SEL originSel = @ selector (setObject: forKey :); Method originMethod = class_getInstanceMethod ([self class], originSel ); SEL overrideSel = @ selector (overrideSetObject: forKey :); Method overrideMethod = class_getInstanceMethod ([self class], overrideSel);/** there are two cases: */if (class_addMethod ([self class], originSel, method_getImplementation (overrideMethod), method_getTypeEncoding (originMethod) {/** case1: NSMutableDictionary does not have-setObject: forKey: implementation of */transform ([self class], overrideSel, method_getImplementation (originMethod), method_getTypeEncoding (originMethod);} else {/** case2: NSMutableDictionary contains-setObject: forKey: */method_exchangeImplementations (originMethod, overrideMethod );}

For the implementation of Swizzling, we need to deal with it in two cases:

Case1: NSMutableDictionary does not have the implementation of-setObject: forKey:. Maybe-setObject: forKey: Is implemented by the NSMutableDictionary parent class. We do not have source code and may happen in any situation. In this case. We need to insert the-setObject: forKey: Method in NSMutableDictionary, and then replace their IMP part.

Case2: NSMutableDictionary already has the implementation of-setObject: forKey:. At this time, we just need to replace their IMP directly and then OK.

So how do I know whether-setObject: forKey: already exists in NSMutableDictionary? Very simple. Use the class_addMethod () method to insert-setObject: forKey: into it. If the original Class is not implemented, the insertion is successful and YES is returned. Otherwise, NO is returned. I will not explain the specific replacement methods in detail. You should also be able to understand the name.

Some may ask, why do we need to consider case1? Can I use case2 directly? The answer is no! Because class_getInstanceMethod () will find the parent Class. If the original Class is not implemented, the method of the parent Class will be replaced. This is not what we want.

The replacement of the parent Class may not affect much, but we 'd better replace the method of the required Class for the sake of security.


This is the flowchart after Swizzling:

  1. External call-setObject: forKey: SEL will jump to-overrideSetObject: forKey: IMP
  2. In the IMP of-overrideSetObject: forKey:, we will call the SEL of-overrideSetObject: forKey:
  3. -The SEL of overrideSetObject: forKey: corresponds to the IMP of-setObject: forKey:

At this time, you should understand the question mentioned above: Why will I call myself in the-overrideSetObject: forKey: implementation?

Finally

Swizzling is indeed risky, so use it with caution. However, it is not necessary to discard food for the sake of fear. As long as we fully understand his principles, we can analyze whether to use it based on the actual situation. Here, I personally think that Swizzling can be used to replace the system's-setObject: forKey: Method to Solve the Problem of online apps using-setObject: forKey: crash for nil.

Refer:

Method Replacement for Fun and Profit

Objective-C hook solution (1): 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.