How to find all the unused Objective-C selector

31 Mar 2020

After several iterations, we may find our iOS project has many unused selectors or class, if we want to clear the code and make the project run faster. We might need to remove some unused code, some unused methods.

Make it short

Get all methods:We can find all the Objective-C methods from linkMap
Get all used selector: Export used selector from MachO file with this command
otool -v -s __DATA __objc_selrefs machOFile
Unused methods: unused methods = All methods - used methods

Here’s the demo project: FindOCUnusedSelectors

link map file Select your target and go to build Settings, search for map, set Write Link Map File to YES, and change the path to somewhere you can find easily. Now build the project, you will get a linkMap.txt file.

Get the MachO file

MachO file

You can find your MachO file after you build your project, just follow the step show above.

With this MachO file you can find a lot of information about you project, you can check this file with Otool, a command line app, or with MachOView, GUI tool. Now we will use this command to show the referenced selectors

otool -v -s __DATA __objc_selrefs TestDemo

Get the unused methods

Download my demo project and open the ununsedSel.py file, change the paths to your project.

Then run the python script with

python3 ununsedSel.py

You will get a file list all the methods and indicate is it used or not.