Posts tagged with: macro

NSLog Conditionally in Debug Mode and NSLog Macros

Using Objective-C Macros to Conditionally Log

During the course of developing and debugging my first iOS apps I’ve realized that there has to be at least a semi-decent way of using log statements for debugging messages as well as error messages without a lot of code overhead and manual changes when switching between building for Release and Debug.

Using macros and compiler settings, you too can quickly separate the statements out and streamline your debugging/logging code.

Creating Your Macros

Find the -Prefix.pch header file for your project and open it for editing. If your project’s name is MyProject you will look for MyProject-Prefix.pch.

Add the following lines to the end of your Prefix header file:

What We Did

I have prefixed each macro with Ash so that there is no confusing them as macros I created. As you can also see, we have created a few different ways to log. We have a standard wrapper for NSLog that we will call instead of NSLog that will only fire if we’ve built using a debug mode flag. We also have two different methods for creating detailed log messages on the fly that will include our log message along with the function and line number the message originates from. The nice thing about these macros is that you can easily change the string format to log in any way that you want.

XCode Settings

  1. Select your project in the Xcode explorer/left pane

    XCode Project

    Xcode 4.2

  2. Select Build Settings in the Xcode center window
  3. Search for preprocessor in the Build Settings section and add DEBUGGING as a Debug Preprocessor Macro.

    Xcode Preprocessor Build Settings

    Set the Debug preprocessor settings