2012-04-03 27 views
1

例如,如果我从XCode(模拟器或连接的iPhone)运行,我想连接到本地数据库。有没有一种方法来识别我是否从XCode运行应用程序

如果它没有从XCode运行,我会连接到我的Web数据库。

我见过类似的东西:

#if TARGET_IPHONE_SIMULATOR 

,但我不知道这是否会为在设备上模拟运行。

+1

这似乎是一个坏主意。这意味着您将拥有只能在没有附加调试器的情况下运行的代码。所以如果你在那里崩溃,那就试试吧。 – 2012-04-03 17:55:47

回答

2

您可以使用Technical Q&A QA1361中的以下代码确定您的应用是否正在调试器下运行。

#include <assert.h> 
#include <stdbool.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <sys/sysctl.h> 

static bool AmIBeingDebugged(void) 
    // Returns true if the current process is being debugged (either 
    // running under the debugger or has a debugger attached post facto). 
{ 
    int     junk; 
    int     mib[4]; 
    struct kinfo_proc info; 
    size_t    size; 

    // Initialize the flags so that, if sysctl fails for some bizarre 
    // reason, we get a predictable result. 

    info.kp_proc.p_flag = 0; 

    // Initialize mib, which tells sysctl the info we want, in this case 
    // we're looking for information about a specific process ID. 

    mib[0] = CTL_KERN; 
    mib[1] = KERN_PROC; 
    mib[2] = KERN_PROC_PID; 
    mib[3] = getpid(); 

    // Call sysctl. 

    size = sizeof(info); 
    junk = sysctl(mib, sizeof(mib)/sizeof(*mib), &info, &size, NULL, 0); 
    assert(junk == 0); 

    // We're being debugged if the P_TRACED flag is set. 

    return ((info.kp_proc.p_flag & P_TRACED) != 0); 
} 

在模拟器和设备(iPhone 4,iOS 5.0.1)下成功测试。

Important Because the definition of the kinfo_proc structure (in ) is conditionalized by __APPLE_API_UNSTABLE, you should restrict use of the above code to the debug build of your program.

+0

我应该如何正确使用此功能?在我的代码中,并使用像:bool debugMode = AmIBeingDebugged(); ? – 2012-04-03 20:39:11

+0

当然,这是行得通的。但将它放在一个单独的文件中,这些文件在需要它的类中导入时似乎更合适。 – 2012-04-03 21:00:07

+0

我收到此错误:语义问题:'AmIBeingDebugged'的静态声明遵循非静态声明 – 2012-04-03 21:37:49

1

您可以让编译器在您的构建中选择不同的代码,具体取决于Debug和Release Build设置中的不同预处理器宏。调试可以使用本地,而发布使用网络。

相关问题