IOS相当于断言失败的abort()

时间:2013-09-17 16:37:10

标签: ios nsassert

当条件为false时,是否有一种简单的方法可以抛出NSAssert生成的异常?为了得到我要求的并行:在C stdlib中,失败的断言导致printf()abort()。在Java中,失败的断言导致java.lang.AssertionError。在ObjectiveC中,一个失败的断言似乎导致(从NSException.h复制):

[[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd
    object:self file:[NSString stringWithUTF8String:__FILE__]
        lineNumber:__LINE__ description:(desc), ##__VA_ARGS__];

我能想到的最好的等价物是将上面的块放在我定义的宏中(让我们称之为NSFail()),或者使用NSAssert(NO, ...)NSFail宏有点不受欢迎,因为我似乎在定义一些本质上已经存在的东西。 NSAssert(NO,...)选项是不受欢迎的,因为我不希望在定义NS_BLOCK_ASSERTIONS时禁用代码。

1 个答案:

答案 0 :(得分:0)

又快又脏:

[[NSException new] raise]

您还可以添加描述性原因:

[[NSException exceptionWithName:@"Impossible" reason:@"Something happened that was not supposed to" userInfo:nil] raise]

NSException apple docs