Skip to content

Instantly share code, notes, and snippets.

@hborders
Created October 23, 2017 14:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hborders/b8b4970501323bb3ddf7992b3699ec63 to your computer and use it in GitHub Desktop.
Save hborders/b8b4970501323bb3ddf7992b3699ec63 to your computer and use it in GitHub Desktop.
How to use Objective-C Generics with -isKindOfClass:
#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