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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user6631314
  • 1,751
  • 1
  • 13
  • 44

2 Answers2

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
Chen Lim
  • 738
  • 7
  • 10
  • 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. – Koh Feb 12 '19 at 09:05
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.

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
  • 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.... – user6631314 Apr 29 '18 at 12:19
  • 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: https://stackoverflow.com/a/24194968/404201 – Jasper Blues Apr 29 '18 at 12:56
  • 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);? – user6631314 Apr 30 '18 at 14:07
  • 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? – user6631314 May 16 '18 at 19:43