Cocoa 如何在main()中但在NSApplicationMain之外使用NSLog?
我读过,这解释了为什么Cocoa 如何在main()中但在NSApplicationMain之外使用NSLog?,cocoa,logging,Cocoa,Logging,我读过,这解释了为什么NSApplicationMain从未真正返回。同样的事情发生在桌面cocoa应用程序中(出于同样的原因),这就是我正在研究的 考虑到这一点,当我的应用程序退出时,如何使用NSLog输出一些最终调试消息? 具体来说,我想做如下工作: int myDebugVariable = 0; int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] ini
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:我熟悉应用程序willterminate
方法,该方法在应用程序即将退出时调用,但不适合我的需要。我的调试代码依赖于某些自定义类的dealloc
方法,因此在调用ApplicationWillTerminate
之前,它不会起作用
更新: 成功了。为了完整起见,这里有一个可行的解决方案:
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;
}
用于注册退出处理程序。当您的应用程序退出时,它将自动被调用,可以通过完成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);
我必须在我的_exit _处理程序中添加另一个NSAutoreleasePool才能使其工作,但它确实起到了作用。非常感谢。如果在退出处理程序中不使用NSLog派生类/基础类,则不需要创建自动释放池。另外,不要忘记,有些类永远不会被释放/释放,即使在终止时也是如此。@jasoncoco:说得好。我已经发现有些类没有发布,但这里值得一提。至于自动释放池,我想printf可以工作,但是我已经习惯了NSLog和NSString,所以我也可以使用它们:)好问题,好答案。谢谢