cocoa - 如何在 main() 中但在 NSApplicationMain 之外使用 NSLog?

标签 cocoa logging

我已阅读questions/559482/why-doesnt-an-iphone-apps-main-function-ever-get-a-chance-to-finish ,这解释了为什么 NSApplicationMain 实际上从未返回。同样的事情发生在桌面 cocoa 应用程序中(出于同样的原因),这就是我正在研究的内容。

考虑到这一点,当我的应用程序退出时,我将如何使用 NSLog 输出一些最终的调试消息?

具体来说,我想做这样的事情:

int myDebugVariable = 0;

int main(int argc, char *argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    CMLog(@"application begin");

    int exitCode = NSApplicationMain(argc,  (const char **) argv);

    CMLog(@"application end. Debugging variable = %d", myDebugVariable);

    [pool release];
    return exitCode;
}

在此示例中,“应用程序开始”行被打印到控制台,但“应用程序结束”行被打印到控制台。线不是。

注意#1:在我的实际代码中,我使用的东西比myDebugVariable更复杂。这是一个简化的示例,说明了我想要实现的效果。

注意#2:我熟悉 ApplicationWillTerminate 方法,该方法在应用程序即将退出时被调用,但它不适合我的需要。我的调试代码依赖于某些自定义类的 dealloc 方法,因此直到调用 ApplicationWillTerminate 后它才会发挥作用。

<小时/>

更新:

Adam Rosenfield's answer成功了。为了完整起见,这是一个可行的解决方案:

int myDebugVariable = 0;

void my_exit_handler(void)
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    CMLog(@"application end: Debugging variable = %d", myDebugVariable);

    [pool release];
}

int main(int argc, char *argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    CMLog(@"application begin");
    atexit(my_exit_handler);

    int exitCode = NSApplicationMain(argc,  (const char **) argv);

    [pool release];
    return exitCode;
}

最佳答案

使用atexit(3)注册一个退出处理程序。当您的应用通过完成 main 或调用 exit(3) 退出时,它将自动调用。例如:

void my_exit_handler(void)
{
    NSLog(@"about to exit, x = %d\n", x);
}

// at some point during app initialization...
atexit(&my_exit_handler);

关于cocoa - 如何在 main() 中但在 NSApplicationMain 之外使用 NSLog?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1016093/

相关文章:

objective-c - 无法从 NSComboBox 检索选定的索引

python - 打印到文件 Beanstalk Worker Tier (Python)

java - 堆栈跟踪和错误中的密码清理

cocoa - 为 Lion 的用户界面恢复功能编码 NSViewController

Postgresql 日志到远程logstash 服务器

python - Django 是否在内部记录用户名

java - Apache BeanUtils.copyProperties 溢出了太多日志

cocoa - Cocos2d V3使用UIImagePickerController类后无法切换场景

ios - NSURLRequest 什么时候超时?

cocoa - CALayer 是否支持矢量艺术还是只处理预渲染的光栅艺术?