Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a class that conforms to a protocol as parameter type?

Is there a way to give, as a parameter, a class that conforms to a certain protocol?

What I tried at first, with a bit of hope, was this:

-(NSString *) getKeyForMyProtocolClass(Class<MyProtocol>)aClass

But that causes

[aClass superclass];

to give the warning "Instance method 'superclass' found instead of class method 'superclass'". I get the same sort of warning for conformsToProtocol:.

Since it gives no such warnings when the parameter is (Class)aClass, it seems Class< MyProtocol> is not actually of the Class type.

I should not be sending NSObject< MyProtocol>, since I need to determine the right key according to the class as well as its superclasses, and only create and add a new object if nothing is set to that key yet.

I could check with conformsToProtocol, but then I'd have to return a nil value which is just messy. I'd prefer to stop the issue at compile time.

So in short, is there a type declaration for a class that conforms to a protocol?

like image 341
Aberrant Avatar asked Oct 26 '11 12:10

Aberrant


1 Answers

You can just typecast your class object to prevent the compiler warning. I was able to do the following:

- (void)tempMethod:(Class<NSObject>)klass {
   id a = [(Class)klass superclass];
    NSLog(@"%@", a);
}

Since you know the type of the object(Class object) you're passing this should work fine.

like image 131
evanescent Avatar answered Oct 01 '22 14:10

evanescent