Created
October 23, 2017 14:27
-
-
Save hborders/b8b4970501323bb3ddf7992b3699ec63 to your computer and use it in GitHub Desktop.
How to use Objective-C Generics with -isKindOfClass:
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 "MyNonClusteredClass.h" | |
@interface GenericIsKindOfClass<ObjectType : MyNonClusteredClass *> : NSObject | |
+ (instancetype _Nonnull)new NS_UNAVAILABLE; | |
- (instancetype _Nonnull)init NS_UNAVAILABLE; | |
- (instancetype _Nonnull)initWithInstanceOfObjectType:(ObjectType _Nonnull)instanceOfObjectType NS_DESIGNATED_INITIALIZER; | |
- (ObjectType _Nullable)typeSafeDowncastOrNil:(NSObject * _Nonnull)object; | |
@end | |
@implementation GenericIsKindOfClass { | |
MyNonClusteredClass * _Nonnull _instanceOfObjectType; | |
} | |
- (instancetype _Nonnull)initWithInstanceOfObjectType:(MyNonClusteredClass * _Nonnull)instanceOfObjectType { | |
NSParameterAssert(instanceOfObjectType); | |
self = [super init]; | |
if (self) { | |
_instanceOfObjectType = instanceOfObjectType; | |
} | |
return self; | |
} | |
- (ObjectType _Nullable)typeSafeDowncastOrNil:(NSObject * _Nonnull)object { | |
if ([object isKindOfClass:[[_instanceOfObjectType class]]) { | |
return (MyNonClusteredClass * _Nonnull) object; | |
} else { | |
return nil; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment