Using Xcode 4 Refactor to rename a class

I had reason recently to want to rename a class within a project. Doing that manually is a pain if you consider all of the places that a class name can be referenced:

  • The contents of the class interface file (.h) and implementation file (.m).
  • The names of the interface (.h) and (.m) files and anywhere that imports the interface file.
  • NIB files
  • The interface and implementation files of any other classes that use the class being renamed.
  • Probably some others that I have forgotten…

Luckily Xcode can take care of all the above for you. The trick is to open the interface file of the class to be renamed, select the class name in the @interface declaration and then from the Xcode Edit menu select Refactor -> Rename…

Xcode then shows a dialog box prompting you for the new name of the class. You should make sure to also select the “Rename related files” checkbox to have Xcode also rename the .h and .m files and fix anywhere that imports the .h file:

At this point Xcode displays all of the files impacted by the rename operation. You can use this to review the changes with Xcode presenting a diff of each file with the old and new versions of the version displayed side-by-side:

Once you have reviewed all of the changes and selected “Save” Xcode provides you a last chance to take a snapshot of the project. Since I am using Git to manage my source code I skip this step:

That is all there is to it. Not something I need to do everyday but it is one of those things that when you need it you need it bad.