【问题标题】:Is there a way to recognize if I'm running app from XCode有没有办法识别我是否从 XCode 运行应用程序
【发布时间】:2012-04-17 10:05:25
【问题描述】:

例如,如果我从 XCode(模拟器或连接的 iPhone)运行,我想连接到本地数据库。

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

我见过类似的东西:

#if TARGET_IPHONE_SIMULATOR

但我不确定它是否适用于在设备上进行模拟。

【问题讨论】:

  • 这似乎是个坏主意。这意味着您将拥有一个只能在没有附加调试器的情况下运行的代码。因此,如果您在那里发生崩溃,请尽情调试它。

标签: iphone objective-c xcode4.2 ios-simulator


【解决方案1】:

您可以使用来自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)下测试成功。

重要因为kinfo_proc结构的定义(在 ) 由 __APPLE_API_UNSTABLE 条件化,您应该 将上述代码的使用限制在程序的调试版本中。

【讨论】:

  • 应该如何正确使用这个功能?在我的代码中使用并使用: bool debugMode = AmIBeingDebugged(); ?
  • 当然可以。但是将它放在一个单独的文件中,然后将其导入那些实际需要它的类中似乎更合适。
  • 我收到此错误:语义问题:“AmIBeingDebugged”的静态声明遵循非静态声明
  • 奇怪。我可以将该函数放置在我想要的任何位置而不会出现任何错误...也许您应该将该函数放置在您的@implementation@interface 之外。看看它是如何在这里完成的,看看是否有帮助:github.com/domesticcatsoftware/DCIntrospect/blob/master/…
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 2021-12-21
    • 2011-09-10
    • 1970-01-01
    • 2022-06-15
    相关资源
    最近更新 更多