NS在线程中使用

sic*_*ckp 5 iphone assert objective-c nsoperation nsthread

我正试图NSAssert在我的iPhone应用程序中使用,以便在发生意外情况时,应用程序失败,并在崩溃日志中崩溃并显示有意义的消息.

如果失败NSAssert在主线程上,这可以正常工作,因为NSInternalInconsistencyException默认情况下它会被捕获并且会停止执行.但我也在后台线程中处理,在这种情况下,NSAssert只是中止线程,但编程继续运行.

我目前的解决方案是在主线程中捕获并重新抛出异常(在本例中为NSOperation's main方法):

- (void)main {
    @try {
        int x = 14;
        ...
        NSAssert1(x > 20, @"x should be greater than 20, was %d", x);
        ...
    }
    @catch (NSException *e) {
        [e performSelectorOnMainThread:@selector(raise) withObject:nil waitUntilDone:YES];
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?也许使用自定义NSAssertionHandler?

我知道我可以使用assert带有静态注释的C :

assert(x > 20 && "x should be greater than 20");
Run Code Online (Sandbox Code Playgroud)

但这不允许我展示实际的失败价值x是什么.

Lau*_*ble 1

您可以将 替换NSAssert为测试代码,然后引发异常。这样,如果断言失败,将引发异常,由@catch块捕获并在主线程上重新引发。

注意:您甚至可以定义 C 宏,以提供紧凑的形式。