Member-only story

Method swizzling in iOS swift

What is method swizzling ?? — this was a question asked in an interview. I didn’t knew the answer back then. I googled it and found many articles about method swizzling. But, I couldn’t understand the proper use case of method swizzling. ’s article on method swizzling was simple and easy to understand. Read it here.

Abhimuralidharan
4 min readDec 21, 2017

--

Today, I was integrating FCM in my iOS app. I saw the same word method swizzling again in the firebase documentation. It said:

So, its an important thing to know. Let’s understand what it is.

What is method swizzling?

Method swizzling is the process of changing the implementation of an existing selector at runtime. Simply speaking, we can change the functionality of a method at runtime.

Note: This is an Objective-C runtime feature.

For example: If you want to track the keys and values added to the UserDefaults and add a prefix string before all the keys, you can switch the implementation of the setValue:forKey method with your own method. So all the calls made to the setValue:forKey method will be routed to the new selector method. You can create the new key string with the prefix added and call the original implementation of setValue:forKey method with the new key. You will be confused whether it will end up in an infinite loop or not. But it will not. (Note: You can do the same by using a category in Objc or extension in swift. Just create a new method and call the super setValue:forKey method from this new method.But what if the imported third party libraries and frameworks use the setValue:forKey method directly. These libraries are not aware of the new custom method as well as our requirement of adding the prefix to the keys. This is when method swizzling comes to play). I took this example from the following article 👇🏻👇🏻👇🏻👇🏻👇🏻👇🏻.

--

--

Abhimuralidharan
Abhimuralidharan

Written by Abhimuralidharan

iOS and tvOS developer, dreamer, photographer 🤨

Responses (7)

Write a response