6

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?

2
  • I have a class that can receive extensions that alter its behaviour. It stores its extensions in a dictionary, the key depends on the class. It has no knowledge of what classes can extend it. The key is the topmost superclass that implements the protocol, so that a class and its superclass won't be doing the same thing, also so other classes can ask if it has a certain extension without having to know all the subclasses of that extension's class. I have it all in place, except for the method signature which now forces me to return nil if the given class does not implement the protocol. Commented Oct 26, 2011 at 18:46
  • Notice: I haven't used Objective-C in a long time. I am not looking for the answer to this question anymore, nor do I feel qualified to judge and accept any answers. I think this question belongs to community votes at this point. Commented Jun 3, 2014 at 21:37

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.