How to detect unused methods and #import in Objective-C

Xcode allows you to (un)check settings for specific compiler warnings that can warn you of some types of unused code. (Select the project in the source list and File > Get Info, then select the Build tab.) Here are a few (which show up for Clang and GCC 4.2 for me) which may be of interest:

  • Unused Functions
  • Unused Parameters
  • Unused Values

I don't see any options for detecting unused imports, but that is a bit simpler — the low-tech approach is just to comment out import statements until you get a compile error/warning.

Unused Objective-C methods are much more difficult to detect than unused C functions because messages are dispatched dynamically. A warning or error can tell you that you have a potential problem, but the lack of one doesn't guarantee you won't have runtime errors.


Edit: Another good way to detect (potentially) unused methods is to examine code coverage from actual executions. This is usually done in tandem with automated unit testing, but doesn't have to be.

This blog post is a decent introduction to unit testing and code coverage using Xcode. The section on gcov (which only works with code generated by GCC, by the way) explains how to get Xcode to build instrumented code that can record how often it has been executed. If you take an instrumented build of your app for a spin in the simulator, then run gcov on it, you can see what code was executed by using a tool like CoverStory (a fairly simplistic GUI) or lcov (Perl scripts to create HTML reports).

I use gcov and lcov for CHDataStructures.framework and auto-generate coverage reports after each SVN commit. Again, remember that it's unwise to treat executed coverage as a definitive measure of what code is "dead", but it can certainly help identify methods that you can investigate further.

Lastly, since you're trying to remove dead code, I think you'll find this SO question interesting as well:

  • Profiling Objective-C binary image size

Appcode has a code inspection feature which finds unused imports and code.


We've been using some homegrown Ruby code, now extracted into a gem called fui: https://github.com/dblock/fui