Emil Loer dot com

The one true Objective-C brace style

Posted on August 24, 2011

Whenever you create a new project in Xcode there are a couple of Objective-C files automatically generated, such as the application delegate. One thing in particular that bothers me about these files is the messy coding style.

One example of this is the inconsistent placing of the opening curly braces. On methods the opening brace is placed on a new line below the method declaration, and on if statements and the like they are placed on the same line.

Most of the templates also have a lot of trailing whitespace, and the Xcode editor itself is rather sloppy when it comes to cleaning that up.

Because I primarily use Vim for my editing needs, I wrote a little function that cleans things up. You can put it in your .vimrc.

function! TransformObjC()
    " correct the code style of an Xcode Objective-C file
    silent! execute "%s/- (/-(/"
    silent! execute "%s/+ (/+(/"
    silent! execute "%s/\\n{\\n/ {\\r/"
    silent! execute "%s/\\ \\+$//"
endfunction

This function does the following:

  • Remove the space between the plus or minus and the return type parenthesis on method signatures.
  • Place the opening curly brace on the same line as the method signature.
  • Clean up any trailing whitespace.

Because these regular expressions only do minor corrections you can call the function as an auto command when you load a new Objective-C file. This can be done as follows in the .vimrc:

autocmd! BufRead *.m call TransformObjC()

Now you can easily mix edits in Vim and Xcode without being annoyed by sloppy formatting. Just remember to reload buffers when going from Xcode to Vim.