What's the point of NSAssert, actually?

后端 未结 10 2036
一个人的身影
一个人的身影 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:24

    Just to clarify, as somebody mentioned but not fully explained, the reason for having and using asserts instead of just creating custom code (doing ifs and raising an exception for bad data, for instance) is that asserts SHOULD be disabled for production applications.

    While developing and debugging, asserts are enabled for you to catch errors. The program will halt when an assert is evaluated as false. But, when compiling for production, the compiler omits the assertion code and actually MAKE YOUR PROGRAM RUN FASTER. By then, hopefully, you have fixed all the bugs. In case your program still has bugs while in production (when assertions are disabled and the program "skips over" the assertions), your program will probably end up crashing at some other point.

    From NSAssert's help: "Assertions are disabled if the preprocessor macro NS_BLOCK_ASSERTIONS is defined." So, just put the macro in your distribution target [only].

提交回复
热议问题