首页 文章

Xcode / iOS:如何确定代码是否在DEBUG / RELEASE构建中运行?

提问于
浏览
198

我正在制作处理敏感信用卡数据的应用程序 .

如果我的代码在调试模式下运行,我想将此数据记录到控制台并进行一些文件转储 .

但是在最终的appstore版本上(即它在发布模式下运行时)必须禁用所有这些(安全隐患)!

我会尽力回答我的问题;所以问题就变成'Is this solution path the right or best way to do it?'

// add `IS_DEBUG=1` to your debug build preprocessor settings  

#if( IS_DEBUG )  
#define MYLog(args...) NSLog(args)  
#else  
#define MYLog(args...)  
#endif

8 回答

  • 93

    在“Apple LVM - 预处理”,“预处理器宏”下检查项目的构建设置以进行调试,以确保设置“DEBUG” - 通过选择项目并单击构建设置选项卡来执行此操作 . 搜索'DEBUG'并查看是否确实设置了DEBUG .

    但请注意 . 您可能会看到DEBUG已更改为另一个变量名称,例如DEBUG_MODE .

    Build Settings tab of my project settings

    然后在源文件中有条件地为DEBUG编码

    #ifdef DEBUG
    
    // Something to log your sensitive data here
    
    #else
    
    // 
    
    #endif
    
  • 229

    有关Swift的解决方案,请参阅SO上的this thread .

    基本上 solution in Swift 看起来像这样:

    #if DEBUG
        println("I'm running in DEBUG mode")
    #else
        println("I'm running in a non-DEBUG mode")
    #endif
    

    此外,您需要通过 -D DEBUG 条目在 Swift Compiler - Custom Flags 部分中为 Swift Compiler - Custom Flags 部分设置 DEBUG 符号 . 请参阅以下屏幕截图以获取示例:

    enter image description here

  • 1

    Apple已在调试版本中包含 DEBUG 标志,因此您无需定义自己的标志 .

    您可能还想考虑在不在 DEBUG 模式时将 NSLog 重新定义为空操作,这样您的代码将更加可移植,您可以只使用常规的 NSLog 语句:

    //put this in prefix.pch
    
    #ifndef DEBUG
    #undef NSLog
    #define NSLog(args, ...)
    #endif
    
  • 7

    大多数答案说如何设置#ifdef DEBUG并且没有人说如何确定调试/发布版本 .

    我的看法:

    • 编辑方案 - >运行 - >构建配置:选择调试/发布 . 它可以控制模拟器和测试iPhone的代码状态 .

    • 编辑方案 - >存档 - >构建配置:选择调试/发布 . 它可以控制测试包应用程序和App Store应用程序的代码状态 .
      enter image description here

  • 21

    zitao xiong的回答非常接近我的用法;我还包括文件名(通过剥离 FILE 的路径) .

    #ifdef DEBUG
        #define NSLogDebug(format, ...) \
        NSLog(@"<%s:%d> %s, " format, \
        strrchr("/" __FILE__, '/') + 1, __LINE__, __PRETTY_FUNCTION__, ## __VA_ARGS__)
    #else
        #define NSLogDebug(format, ...)
    #endif
    
  • 86

    在xcode 7中, Apple LLVM 7.0 - preprocessing 下有一个字段,称为“预处理器宏未在预编译中使用...”我将 DEBUG 放在Debug前面,它通过使用下面的代码对我有用:

    #ifdef DEBUG
        NSString* const kURL = @"http://debug.com";
    #else
        NSString* const kURL = @"http://release.com";
    #endif
    
  • 2

    不确定我是否回答了你的问题,也许你可以试试这些代码:

    #ifdef DEBUG
    #define DLOG(xx, ...)  NSLog( \
        @"%s(%d): " \
        xx, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__ \  
        )
    #else
    #define DLOG(xx, ...)  ((void)0)
    #endif
    
  • 8

    还有一个想法是检测:

    DebugMode.h

    #import <Foundation/Foundation.h>
    
    @interface DebugMode: NSObject
        +(BOOL) isDebug;
    @end
    

    DebugMode.m

    #import "DebugMode.h"
    
    @implementation DebugMode
    +(BOOL) isDebug {
    #ifdef DEBUG
        return true;
    #else
        return false;
    #endif
    }
    @end
    

    添加到头桥文件中:

    #include "DebugMode.h"

    用法:

    DebugMode.isDebug()

    不需要在项目属性swift标志内写一些东西 .

相关问题