Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created March 13, 2013 12:09
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyrtsa/5151517 to your computer and use it in GitHub Desktop.
Save pyrtsa/5151517 to your computer and use it in GitHub Desktop.
"Safe" casting in Objective-C using `instancetype`.
#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");
}
@iNono22
Copy link

iNono22 commented Jan 16, 2015

Nice catch;
Thanks

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