Instantly share code, notes, and snippets.

Embed
What would you like to do?
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