Created
March 13, 2013 12:09
-
-
Save pyrtsa/5151517 to your computer and use it in GitHub Desktop.
"Safe" casting in Objective-C using `instancetype`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSObject (Cast) | |
+ (instancetype)cast:(id)object; | |
@end | |
@implementation NSObject (Cast) | |
+ (instancetype)cast:(id)object | |
{ | |
return [object isKindOfClass:self] ? object : nil; | |
} | |
@end | |
void example() | |
{ | |
id a = @"a"; | |
NSObject *b = [NSObject cast:a]; // okay, @"a" is an NSObject. | |
NSString *c = [NSString cast:a]; // okay, @"a" is an NSString. | |
NSNumber *d = [NSNumber cast:a]; // nil; a string is not a number | |
NSCAssert(b && c && !d, @"objects are only nil where casts failed"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice catch;
Thanks