- @protocol MyProtocol
- - (void) doSomething;
- @end
- @interface MyClass : NSObject<MyProtocol>//直接符合协议的类
- {
- }
- @end
- @implementation MyClass
- - (void) doSomething {
- }
- @end
- @interface MyOtherClass : MyClass//继承了符合协议的类,即其父类符合协议。
- {
- }
- @end
- @implementation MyOtherClass
- - (void) doSomething {
- }
- @end
- int main (int argc, const char * argv[])
- {
- NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
- MyClass *obj_one = [MyClass new];
- BOOL one_conforms = [obj_one conformsToProtocol:@protocol(MyProtocol)];
- MyOtherClass *obj_two = [MyOtherClass new];
- //obj_two是类的实例对象,和父类相关,其父类符合协议,则其亦符合。
- BOOL two_conforms = [obj_two conformsToProtocol:@protocol(MyProtocol)];
- NSLog(@"obj_one conformsToProtocol: %d", one_conforms);//output:YES
- NSLog(@"obj_two conformsToProtocol: %d", two_conforms);//output:YES
- [pool drain]; return 0;
- }
- //Output:
- obj_one conformsToProtocol: 1
- obj_two conformsToProtocol: 1
- //Whereas:
- MyOtherClass *obj_two = [MyOtherClass new];
- //class_conformsToProtocol是只检查当前类符不符合协议,和其父类无关。
- BOOL conforms_two = class_conformsToProtocol([obj_two class], @protocol(MyProtocol));
- NSLog(@"obj_two conformsToProtocol: %d", conforms_two);//output:NO
- //Output:
- obj_two conformsToProtocol: 0