What's the point of NSAssert, actually?

后端 未结 10 2064
一个人的身影
一个人的身影 2020-12-04 05:43

I have to ask this, because: The only thing I recognize is, that if the assertion fails, the app crashes. Is that the reason why to use NSAssert? Or what else is the benefit

10条回答
  •  天涯浪人
    2020-12-04 06:12

    NSAssert gives you more than just crashing the app. It tells you the class, method, and the line where the assertion occurred. All the assertions can also be easily deactivated using NS_BLOCK_ASSERTIONS. Thus making it more suitable for debugging. On the other hand, throwing an NSException only crashes the app. It also does not tell about the location of the exception, nor can it be disabled so simply. See the difference in the images below.

    The app crashes because an assertion also raises an exception, as the NSAssert documentation states:

    When invoked, an assertion handler prints an error message that includes the method and class names (or the function name). It then raises an NSInternalInconsistencyException exception.

    NSAssert:

    Logs after an assertion

    NSException:

    Logs after an exception

提交回复
热议问题