Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare an ObjC parameter that's a Class conforming to a protocol

Tags:

In Objective-C, it is possible to pass a class as a parameter to a method:

- (void) methodThatTakesClass:(Class)theClass; 

And it is possible to pass an instance that is conforming to a protocol as a parameter:

- (void) myConformInstance:(id <MyProtocol>)theObject; 

Is it possible to use the combined functionality? A method which takes a class which is conforming to a certain protocol.

like image 233
Mats Stijlaart Avatar asked Aug 03 '11 18:08

Mats Stijlaart


Video Answer


1 Answers

Yes. The following is a valid program which will log the NSObject class.

#import <Foundation/Foundation.h> void f(Class <NSObject> c) {     NSLog(@"%@",c); } int main() {     f([NSObject class]); } 

This would cause a compiler error if you tried to pass a class which doesn't conform to NSObject, such as the Object class. You can also use it for methods.

- (void)printClass:(Class <NSObject>)c; 
like image 146
ughoavgfhw Avatar answered Sep 29 '22 15:09

ughoavgfhw