Using Pragma Mark
Xcode is by far the best IDE I’ve ever used for development and one of my favourite features is the ability to get the source code within a file organised into categories using
#pragma mark - Category.
- It makes it easier to read and navigate through your own source code.
- If you and your team agree on a particular convention to follow, it will also make it easier for you to navigate through code written by others.
- When organising your code, you will end up grouping related methods together so they fit the category they are listed under. This will allow you to easily isolate these method groups into separate classes if required at a later time.
I usually make a category for each of the following items, but it’s really up to your personal preference as to what and how you choose these category groups. The idea here is to just group related methods together to keep the code easy to follow.
- Init / Setup Methods
- View Life-cycle (in UIViewController for example)
- Overrides (Subclass method overrides)
- Public Methods
- Private Methods
- Protocol Methods
- Class Methods
Here’s what it looks like
From the jump bar you can view all the categories and methods within a file.
Code Snippets Shortcut
I found having to type in
#p - then wait for autocomple to fill in the rest of
pragma, and then typing
mark - my title to be a bit mundane (what can I say - I’m a bit lazy). So I’ve made my own code snippet to speed up the process.
Creating a code snippet
1) First expand the utilities sidebar
2) Open the Code Snippet tab at the bottom
3) Now somewhere in your source file type in
#pragma mark - <#title#>
4) Select the entire line and drag it to the code snippet area in the sidebar. If that works you should see a popup similar to the one below.
5) Fill in an appropriate title and summary
6) The completion shortcut is what will be used to trigger the snippet from the autocomplete menu so choose something short that does not conflict with any of your other snippets.
7) For the completion scopes you want to add
- Top Level
- Class implementation
8) Click Done and your Done!
Seeing your shortcut in action
In your source file start typing in your shortcut and you should see your new snippet appear in the auto complete menu.
On selecting it or pressing the return key,
#pragma mark - will be filled in and the cursor will be in right position ready to type in the category title.
So it seems there is a bug with Xcode which prevents the first pragma mark from appearing in the list if your implementation or interface does not make use of the braces (see link). The work around is to simply add the braces.