Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether an object conforms to two separate protocols in Objective-C

In Objective-C when you declare an instance variable you can check if it conforms to a protocol on assignment at compile time like so:

id <MyProtocol> variable;

Is it possible to check whether an object assigned to the variable conforms to two separate protocols at compile time? As in:

id <MyProtocol, MyOtherProtocol> variable;

I know I can do runtime checking using conformsToProtocol: and respondsToSelector et al, (which I do before actually using the object for added safety), and I could write my own setter method that does the check, but I'd like to know at compile time.

like image 924
Jasarien Avatar asked Jan 10 '11 11:01

Jasarien


2 Answers

Yes, that syntax is correct.

The correct way to check if an object conforms to a protocol is to do this:

if ([myObj conformsToProtocol:@protocol(MyProtocol)]) {
  //conformance!
}

Note that this works as both an instance method and a class method.

If for some bizarre reason you can't use the conformsToProtocol:, you can drop down to the runtime level:

#import <objc/runtime.h>

Protocol * p = objc_getProtocol("MyProtocol");
if (class_conformsToProtocol([myObj class], p)) {
  //conformance!
}
like image 128
Dave DeLong Avatar answered Sep 21 '22 00:09

Dave DeLong


I think the best is to use your own code:

id <MyProtocol, MyOtherProtocol> variable;

And before calling a method, check if the variable responds to what you want to call:

if ([variable respondsToSelector:@selector(aMethod:)]) {
    [variable aMethod:nil];
}

Since Objective-C is a dynamic language, just declaring the variable protocol can't assure that it conforms to the protocol. It'll mostly generates warnings when you build.

like image 20
Felipe Cypriano Avatar answered Sep 22 '22 00:09

Felipe Cypriano