I have come across some strange behavior in my iPhone Objective-C app.
I am using some code to test an object:
if (!class_conformsToProtocol([someVar someFunctionThatReturnsAClass], @protocol(MyProtocol)))
[NSException raise:@"Invalid Argument" format:@"The variables returned by 'someFunctionThatReturnsAClass' Must conform to the 'myProtocol' protocol in this case."];
Oddly, when I have a class that looks like this:
@interface BaseClass : NSObject<MyProtocol>
...
@end
@interface SubClass : BaseClass
...
@end
And when I call this fragment: class_conformsToProtocol([SubClass class], @protocol(MyProtocol)), it returns NO.
Also, this code fails:
class_conformsToProtocol([NSString class], @protocol(NSObject)); // also returns NO
While this code returns YES:
[NSString conformsToProtocol:@protocol(NSObject)];
Is there anything I am missing in the docs?
Or is this a bug of some sort? (I am on iOS 4.2 if that matters any).
Use
NSObject‘sconformsToProtocol:method.Here’s an experiment I tried:
Output:
Whereas:
Output:
Verdict:
This is a bug with
class_conformsToProtocol, use theconformsToProtocol:method ofNSObjectUnlike
class_conformsToProtocol,NSObject‘sconformsToProtocol:method will check superclasses as well.