Iphone Objective-C class_-Rotocol()错误?

Iphone Objective-C class_-Rotocol()错误?,iphone,objective-c,class,protocols,Iphone,Objective C,Class,Protocols,我在iPhone Objective-C应用程序中遇到了一些奇怪的行为 我正在使用一些代码来测试一个对象: if (!class_conformsToProtocol([someVar someFunctionThatReturnsAClass], @protocol(MyProtocol))) [NSException raise:@"Invalid Argument" format:@"The variables returned by 'someFunctionThatRetur

我在iPhone Objective-C应用程序中遇到了一些奇怪的行为

我正在使用一些代码来测试一个对象:

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."];
奇怪的是,当我有一个这样的类:

@interface BaseClass : NSObject<MyProtocol>

...

@end

@interface SubClass : BaseClass

...

@end
当此代码返回
YES

[NSString conformsToProtocol:@protocol(NSObject)];
文件里有我遗漏的东西吗?
或者这是某种错误?(如果有必要的话,我使用的是iOS 4.2)。

使用
NSObject
的方法

下面是我尝试过的一个实验:

@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];
    BOOL two_conforms  = [obj_two conformsToProtocol:@protocol(MyProtocol)];
    NSLog(@"obj_one conformsToProtocol: %d", one_conforms);
    NSLog(@"obj_two conformsToProtocol: %d", two_conforms);

    [pool drain];
    return 0;
}
鉴于:

MyOtherClass *obj_two = [MyOtherClass new];
BOOL conforms_two = class_conformsToProtocol([obj_two class], @protocol(MyProtocol));
NSLog(@"obj_two conformsToProtocol: %d", conforms_two);
输出:

obj_one conformsToProtocol: 1
obj_two conformsToProtocol: 1
obj_two conformsToProtocol: 0
判决:

这是一个带有
类\u conformsToProtocol
的bug,请使用
NSObject的
conformsToProtocol:
方法


class\u conformsToProtocol
不同,
NSObject
conformsToProtocol:
方法也会检查超类。

如果这里有bug,它就在文档中

根据源代码,
class\u conformsToProtocol()
使用
class\u copyprotocolist()
,然后根据参数测试每个生成的协议
class\u copyProtocolList()
被记录为仅返回给定类采用的协议,而不是超类采用的协议<因此,代码>类只测试给定类是否采用协议,而不测试其超类是否采用协议


文档错误在于
class\u conformsToProtocol()
没有说明此行为。但是,文档中确实指出,通常不应使用该函数,而应使用
NSObject
conformsToProtocol:
方法。

哇,这很有趣……不是bug<代码>类_conformsToProtocol()
不检查超类。这是经过设计的,因为迭代超类很简单。这和它们之间的区别是一样的。在本例中,您正在寻找
conformsToProtocol:
方法(您可以调用您得到的类)。实际上,我来这里是想寻找一种方法来检查子类与协议的一致性——忽略父类的一致性(反之亦然),所以感谢您提出这个问题!:)@ethanB很明显,我知道正确的调用方法,就像在我的帖子里一样,其他的回答都是:)这很有趣,但你一针见血。一般来说,如果有一个Objective-C函数做同样的事情,你真的不应该使用C函数。Ex objc_加载模块vs NSBundle
obj_two conformsToProtocol: 0