Using a Custom Assertion Handler

In some cases, you might want to define your own assertion handler to print error messages to a different error console or to raise custom exceptions, instead of the generic NSInternalInconsistencyException. To implement these features, you must define a subclass of NSAssertionHandler and override its handleFailureInMethod:object:file:lineNumber:description: and handleFailureInFunction:file:lineNumber:description: methods to handle assertions in methods and functions, respectively.

To add your assertion handler to a thread, you must add the assertion handler to the thread’s attributes dictionary. Use the current NSThread’s threadDictionary method to retrieve the dictionary. Add your assertion-handler object to the dictionary using the key NSAssertionHandler. This technique is used to specify a custom assertion handler on any thread, including the main thread. You must execute these steps in the thread which you wish to modify; one thread cannot modify the thread attributes dictionary of another.

Typically, you should add your assertion handler to the thread dictionary immediately after creating the thread. However, a default assertion handler is not created until an assertion macro is encountered and you can always replace the existing assertion handler in the thread dictionary. If your assertion handler already exists in the thread dictionary, it is used in place of the default assertion handler.