NSAssertionHandler

Programming incorporates numerous disciplines of human reasoning, from high-level discourse and semantics—the “story” we tell each other to explain how a system works—to the mathematical and philosophical machinery that underpins everything.

Assertions are a concept borrowed from classical logic. In logic, assertions are statements about propositions within a proof. In programming, assertions denote assumptions the programmer has made about the application at the place where they are declared.

nshipster.com/nsassertionhandler/

Assertions are statements that check assumptions in code. If they fail, they stop the program and show an error.

In Objective-C, Foundation has macros like NSAssert for methods and NSCAssert for functions. They also have versions for parameters: NSParameterAssert and NSCParameterAssert. These call NSAssertionHandler, which prints a message and raises an exception. Each thread has its own handler.

You can subclass NSAssertionHandler to handle failures differently, such as logging them instead of crashing. Set your subclass on the main thread early in the app. Assertions are off in release builds by default. Use them with unit tests to define and check code behaviour.

Assertions help catch errors early but use them carefully in live apps.


Category:

Year: