Skip to content

Instantly share code, notes, and snippets.

@lilyball
Created August 19, 2012 04:19
Show Gist options
  • Save lilyball/3391903 to your computer and use it in GitHub Desktop.
Save lilyball/3391903 to your computer and use it in GitHub Desktop.
+[NSObject cast:]
@interface NSObject (Cast)
+ (instancetype)cast:(id)from;
@end
@implementation NSObject (Cast)
+ (instancetype)cast:(id)from {
if ([from isKindOfClass:self]) {
return from;
}
return nil;
}
@end
@asmallteapot
Copy link

The usage here is basically this, right?

UIButton *someButton = [UIButton new];
UIView *buttonView = [UIView cast:someButton];

@lilyball
Copy link
Author

That's backwards. You don't need a cast to assign a UIButton value to a UIView. It's more like

UIButton *button = [UIButton cast:someView];
if (button != nil) {
    // someView was a button
}

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