Liftoff
Liftoff

Reputation: 25412

Passing a Class which conforms to a protocol as an argument

Is there a way in Obj-C to pass a class as a parameter which conforms to a protocol?

For example, say I have a slew of classes which conform to this protocol:

@protocol IMyProtocol <NSObject>

+ (id)someMethodINeed;

@end

I want to set up a method which takes in any class which conforms to this protocol.

@interface SomeClass : NSObject <IMyProtocol>

@interface AnotherClass : NSObject<IMyProtocol>

I want to make a method like this:

- (void)doSomething:(Class<IMyProtocol>)customClass
{
    [customClass someMethodINeed];
    //A whole bunch of other code I don't want to copy/paste each time
}

And call it with any of those classes

[self doSomething:SomeClass];
[self doSomething:AnotherClass];

I can't figure out the syntax though. Is this possible?

Upvotes: 1

Views: 197

Answers (1)

CRD
CRD

Reputation: 53010

To make your code work you just need to pass the class, change your two calls to:

[self doSomething:SomeClass.class];
[self doSomething:AnotherClass.class];

However while this works the compiler is not doing the checks you probably expect. You can pass any class to doSomething: regardless of whether it implements your protocol; and [customClass someMethodINeed] is a dynamic call resolved (or not) at runtime and may produce an "unrecognized selector sent to class" error.

(Objective-C always does dynamic method lookup but with typed values the compiler is usually able to determine at compile time whether the runtime resolution will succeed or not. What you are are seeing here is the behavour you get when you program using id.)

Upvotes: 1

Related Questions