Skip to content

Instantly share code, notes, and snippets.

@Tricertops
Created July 29, 2013 15:06
Show Gist options
  • Save Tricertops/6104989 to your computer and use it in GitHub Desktop.
Save Tricertops/6104989 to your computer and use it in GitHub Desktop.
My variant of Assertion macros
#if !defined(NS_BLOCK_ASSERTIONS)
#define MTKAssert(CONDITION, MESSAGE, ...)\
if ( ! (CONDITION) && (( [[NSAssertionHandler currentHandler] handleFailureInFunction:[NSString stringWithUTF8String:__PRETTY_FUNCTION__] file:[NSString stringWithUTF8String:__FILE__] lineNumber:__LINE__ description:MESSAGE, ##__VA_ARGS__], YES)) )
#else
#define MTKAssert(CONDITION, MESSAGE, ...)\
if ( ! (CONDITION) && (( NSLog(@"*** Assertion failure in %s, %s:%d, Condition not satisfied: %s, reason: '" MESSAGE "'", __PRETTY_FUNCTION__, __FILE__, __LINE__, #CONDITION, ##__VA_ARGS__), YES)) )
#endif
#define MTKAssertReturn(CONDITION, MESSAGE, ...) ESSAssert(CONDITION, MESSAGE, ##__VA_ARGS__) return
#define MTKAssertReturnNil(CONDITION, MESSAGE, ...) ESSAssert(CONDITION, MESSAGE, ##__VA_ARGS__) return nil
#define MTKAssertException(CONDITION, MESSAGE, ...) ESSAssert(CONDITION, MESSAGE, ##__VA_ARGS__) @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"*** Assertion failure in %s, %s:%d, Condition not satisfied: %s, reason: '" MESSAGE "'", __PRETTY_FUNCTION__, __FILE__, __LINE__, #CONDITION, ##__VA_ARGS__] userInfo:nil]
// Normal usage.
// DEBUG: Throw assetion exception (just like NSAssert).
// RELEASE: Log message.
MTKAssert(result != nil, @"Message");
// Use with conditioned "safety" code.
// DEBUG: Throw assetion exception (just like NSAssert).
// RELEASE: Log message and execute the following code.
// (Important: In the first example, the ";" (semicolon) was the additional code to execute on RELEASE.)
MTKAssert(result != nil, @"Message") {
result = placeholder;
}
// Convenience. Calls "return;" if condition is not met.
MTKAssertReturn(result != nil, @"Message");
// Convenience. Calls "return nil;" if condition is not met.
MTKAssertReturnNil(result != nil, @"Message");
// Convenience. Throws exception even on RELEASE.
MTKAssertException(result != nil, @"Message");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment