NSAssert vs. assert: Which do you use, and when?

Objective CAssert

Objective C Problem Overview


I've read two really interesting pieces of advice, recently:

  1. In the comments to this StackOverflow answer, @Mike Weller says to leave your asserts on in production code... what's the performance hit, really? Is there any reason NOT to leave them in?
  2. In Vincent Gable's blog, he states that you should prefer assert over NSAssert... is there any reason NOT to use assert? (it's less letters :))

Objective C Solutions


Solution 1 - Objective C

To answer your two questions:

  1. There should be very little performance hit for leaving in an assertion, unless the actual action in the assertion is time consuming (e.g. assert([obj calculateMeaningOfLife] == 42)). An assertion should be no different than an extra if statement, performance-wise. The reason for stripping out assertions in release builds is that they are essentially a debugging tool--they catch inconsistent internal program state at runtime. From a developer perspective, it's much better for an app to crash as soon as something goes wrong, but from a user perspective it's arguably less annoying if the app doesn't crash (unless letting the app run with abnormal state causes something horrible to happen), and exposing development details in error messages can be off-putting. There are good arguments on both sides--if I remember correctly, Code Complete recommends stripping them out but The Pragmatic Programmer recommends leaving them in. In any case, assertions are not a substitute for proper error handling and should only be used for programming errors.

  2. The basic difference between an NSAssert and a regular assert is that an NSAssert raises an exception when it fails while an assert just crashes the app. NSAssert also lets you supply fancier error messages and logs them. Practically, I really don't think there's much difference between the two--I can't think of a reason to handle an exception thrown by an assertion. (To split hairs, I think NSAssert usually involves less typing because you don't have to include assert.h, but that's neither here nor there.)

Solution 2 - Objective C

NSAssert() macro should be used only within Objective-C methods.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDan RosenstarkView Question on Stackoverflow
Solution 1 - Objective CshostiView Answer on Stackoverflow
Solution 2 - Objective CFreemanView Answer on Stackoverflow