Skip to content

Instantly share code, notes, and snippets.

@asmallteapot
Last active March 31, 2016 23:19
Show Gist options
  • Save asmallteapot/0b0b2494112b0f4882505996d57c2b11 to your computer and use it in GitHub Desktop.
Save asmallteapot/0b0b2494112b0f4882505996d57c2b11 to your computer and use it in GitHub Desktop.
Safe Casting in Objective-C with macros.
#define ASTCastInline(valueIn, ObjectType) \
([valueIn isKindOfClass:[Type class]] ? (Type *)valueIn : nil)
#define ASTCast(valueIn, ObjectType, valueOut) \
ObjectType *valueOut = ([valueIn isKindOfClass:[ObjectType class]] ? (ObjectType *)valueIn : nil);
- (IBAction)somethingHappened:(id)sender {
ASTCast(sender, UIButton, button);
ASTCast(sender, UIGestureRecognizer, recognizer);
if (button) {
NSLog(@"Invoked by button: %@", button);
} else if (recognizer) {
NSLog(@"Invoked by gesture recognizer: %@", recognizer);
} else {
NSLog(@"Invoked by unknown sender: %@", sender);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment