How to Organize Your iOS App Code Using the #pragma mark Statement

By Jesse Feiler

This is a good time to introduce the #pragma mark statement for iOS apps. If you look in DetailViewController.m, you can see how this statement can be used to group things in your file; such statements are also displayed in the list of symbols.

You use the #pragma mark statement with a label (such as View life cycle or Animation) to add a category header in the Methods list so that you can identify and keep separate the methods that fit logically in the list.

For example, in the DetailViewController template, you could add

#pragma mark - Managing the detail item

The first part of the statement (with a space and a dash) places a horizontal line in the Methods list. The second one places the text “Managing the detail item” in the Methods list.

This is a useful trick for finding code sections, organizing your code, and adding new code in the proper sections.

Some sections for your code are easy to identify, but, as you’ll see in some of the sample code, developers differ as to how they organize their code. Should go in a section called User Interface or Initialization? Do whatever makes the most sense to you. It’s probably a good idea to stick with the code sections in the templates and sample code at least to start.