Skip to content

Instantly share code, notes, and snippets.

@krzysztofzablocki
Created July 3, 2013 18:52
Show Gist options
  • Save krzysztofzablocki/5921645 to your computer and use it in GitHub Desktop.
Save krzysztofzablocki/5921645 to your computer and use it in GitHub Desktop.
My take on assertions, code sample accompanying blog post at http://merowing.info/2013/07/expanded-use-of-asserts/
typedef NS_ENUM(NSInteger, kErrorCode) {
kErrorCodeInternal = 431432,
};
//! generate error and log it.
extern NSError *pixle_NSErrorMake(NSString *message, NSUInteger code, NSDictionary *aUserInfo, SEL selector);
#define AssertTrueOrReturnBlock(condition, block) do{ NSAssert((condition), @"Invalid condition not satisfying: %s", #condition);\
if(!(condition)) { block(pixle_NSErrorMake([NSString stringWithFormat:@"Invalid condition not satisfying: %s", #condition], kErrorCodeInternal, nil, _cmd)); return;} }while(0)
#define AssertTrueOrReturn(condition) do{ NSAssert((condition), @"Invalid condition not satisfying: %s", #condition);\
if(!(condition)) { pixle_NSErrorMake([NSString stringWithFormat:@"Invalid condition not satisfying: %s", #condition], kErrorCodeInternal, nil, _cmd); return;} } while(0)
#define AssertTrueOrReturnNilBlock(condition, block) do{ NSAssert((condition), @"Invalid condition not satisfying: %s", #condition);\
if(!(condition)) { block(pixle_NSErrorMake([NSString stringWithFormat:@"Invalid condition not satisfying: %s", #condition], kErrorCodeInternal, nil, _cmd)); return nil;} } while(0)
#define AssertTrueOrReturnNil(condition) do{ NSAssert((condition), @"Invalid condition not satisfying: %s", #condition);\
if(!(condition)) { pixle_NSErrorMake([NSString stringWithFormat:@"Invalid condition not satisfying: %s", #condition], kErrorCodeInternal, nil, _cmd); return nil;} while(0)
#define AssertTrueOrReturnError(condition) do{ NSAssert((condition), @"Invalid condition not satisfying: %s", #condition);\
if(!(condition)) { return pixle_NSErrorMake([NSString stringWithFormat:@"Invalid condition not satisfying: %s", #condition], kErrorCodeInternal, nil, _cmd);} }while(0)
@samdods
Copy link

samdods commented Feb 14, 2014

Hey Kzrys, you don't need [NSString stringWithFormat:@"Invalid condition not satisfying: %s", #condition] you can simply do

@"Invalid condition not satisfying: " #condition

Because the compiler will attach the strings together for you.

My totally dry version is here: https://gist.github.com/samdods/8979831 I admit it's perhaps a little too dry in places, if there is such a thing! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment