NSAssert vs. assert: what do you use and when?

I recently read two really interesting tips:

  • In the comments on https://stackoverflow.com/a/4129608/12828 , @ Mike Weller says to leave your statements in the production code ... what really hit the performance? Is there any reason NOT to leave them?
  • On the Vincent Gable blog , he claims that you should prefer assert over NSAssert ... is there any reason NOT to use assert ? (it's less letters :))
+44
objective-c assert
Jul 07 '11 at 19:55
source share
2 answers

To answer two questions:

  • A statement should have very little performance if the actual action in the statement does not take much time (for example, assert([obj calculateMeaningOfLife] == 42) ). The statement should not differ from the optional if in terms of performance. The reason for withdrawing assertions in release builds is that they are essentially a debugging tool — at runtime, they detect an inconsistent internal state of the program. From the developer's point of view, it is much better for the application to crash as soon as something goes wrong, but from the user's point of view, it is probably less annoying if the application does not crash (unless launching the application with an abnormal state will lead to something horrible), and exposing development details in error messages can be turned off. There are good arguments on both sides - if I remember correctly, Code Complete recommends deleting them, but the Pragmatic programmer recommends leaving them. In any case, statements do not replace correct error handling and should only be used for programming errors.

  • The main difference between NSAssert and regular assert is that NSAssert throws an exception when it fails, and assert just crashes the application. NSAssert also allows you to send error messages and log them. In practice, I really don't think that there is a big difference between the two - I cannot think of a reason to handle the exception raised by the statement. (To separate the hair, I think NSAssert usually includes less typing because you don't need to include assert.h , but it is neither here nor there.)

+52
Jul 08 '11 at 6:30 a.m.
source share
The NSAssert () macro should only be used in Objective-C.

NSAssert () is disabled if the NS_BLOCK_ASSERTIONS preprocessor macro is defined (usually in the release version).

+4
Oct. 25 2018-11-11T00:
source share



All Articles