What's the point of NSAssert, actually?

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

    I can't really speak to NSAssert, but I imagine that it works similarly to C's assert().

    assert() is used to enforce a semantic contract in your code. What does that mean, you ask?

    Well, it's like you said: if you have a function that should never receive a -1, you can have assert() enforce that:

    void gimme_positive_ints(int i) {
      assert(i > 0);
    }
    

    And now you'll see something like this in the error log (or STDERR):

    Assertion i > 0 failed: file example.c, line 2
    

    So not only does it safe-guard against potentially bad inputs but it logs them in a useful, standard way.

    Oh, and at least in C assert() was a macro, so you could redefine assert() as a no-op in your release code. I don't know if that's the case with NSAssert (or even assert() any more), but it was pretty useful to compile out those checks.

提交回复
热议问题