3

Because NSLog statements slow down apps, it seems advisable to remove them prior to release. A number of older answers on SO going back to 2010 suggest putting some code in the pch file such as:

#ifndef DEBUG
   #define NSLog(...);
#endif

However, Xcode no longer automatically creates a pch file. I gather it is possible to manually create a pch file but this seems like a bit of a kludge. Is manually creating a pch file and adding the above code to it still the recommended way to comment out NSLog statements prior to release or is there a more modern approach?

2 Answers 2

2

All the old answers I found (including adding a PCH file) didn't work for Swift. Here's what finally worked for me:

  1. Define the DEBUG flag by adding "-D DEBUG" to "Other Swift Flags" in the build settings.
  2. Add the following global code (I just put it in a file named Globals.swift):
#if !DEBUG
public func NSLog(_ format: String, _ args: CVarArg...) {
}    

public func print(_ items: Any..., separator: String = " ", terminator: String = "\n") {
}
#endif
Sign up to request clarification or add additional context in comments.

1 Comment

Is it necessary to define DEBUG flag inside the "Other Swift Flags"? I have tested the #if DEBUG and so long the build configuration is set to Release in edit scheme, the code inside the #if DEBUG will not get printed to console.
1

It is still possible to create a pre-compiled header, however this is discouraged, at least by default. To do this, edit the build settings for your target, and define a path to a Prefix Header.

Prefix Header

Use a Logging Library

Perhaps you can use a logging library, like CocoaLumberJack, or here is a very simple one, that nonetheless works well.

4 Comments

If you already have a lot of NSLog statements in the code, would you recommend going the pch route? Is that what people do? I would imagine there are still many developers who use NSLog statements who need to remove them at release time....
Depends on reqs and what project is for, but generally recommend to use a logging lib over NSLog - can do things like log at 'info' level for release and trace for debug. You could do a search/replace to introduce a lib. Related discussion about pch files: stackoverflow.com/a/24194968/404201
for the simple logger, do I have to import the library into every file where I have a log statement ie import "OCLogTemplate.h"? And would I just rewrite all my NSLog ("name:%@ and id%d for item",_item.name,_item.id);statements as LogDebug("name:%@ and id%d for item",_item.name,_item.id);?
In the readme file, you say it is preferred to flip switches in build settings. Can you provide an example of where to do this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.