2009-06-19 4 views
1

나는 questions/559482/why-doesnt-an-iphone-apps-main-function-ever-get-a-chance-to-finish을 읽었는데, 이는 NSApplicationMain이 실제로 반환되지 않는 이유를 설명합니다. 같은 일이 데스크톱 코코아 애플리케이션에서 (같은 이유로) 발생합니다. 이는 제가 수행하고있는 작업입니다.main()에서는 NSLog를 사용할 수 있지만 NSApplicationMain 외부에서는 NSLog를 어떻게 사용할 수 있습니까?

염두에두고 내 응용 프로그램이 종료 될 때 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; 
} 
+0

exit 처리기에서 NSLog 파생 클래스/Foundation 클래스를 사용하지 않으면 자동 복구 풀을 만들 필요가 없습니다. 또한 종료시에도 일부 클래스는 할당 취소/해제되지 않음을 잊지 마십시오. –

+0

@Jason Coco : 좋은 지적입니다. 나는 이미 일부 수업은 발표되지 않았 음을 발견했지만 여기서 언급 할 것입니다. autorelease 풀에 관해서는, printf가 작동한다고 생각하지만, NSLog와 NSString에 익숙해 져서 사용할 수 있습니다. :) –

+0

위대한 질문과 훌륭한 답변. 감사! –

답변

3

사용 atexit(3)가 종료 핸들러를 등록 : 완성도를 위해서, 여기에 작업 솔루션입니다. 기본 완료 또는 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); 
+0

이 작업을 위해 my_exit_handler에 다른 NSAutoreleasePool을 추가해야했지만 확실히 트릭을 수행했습니다. 고맙습니다! –

관련 문제