iPhone如何指定Class数据类型必须采用的协议 [英] iphone how to specify the Class data type have to adopt to a protocol
问题描述
在我的应用程序中,我需要返回类"作为返回类型,如:
In my application, I need to return the "Class" as a return type like:
Application.m:
Application.m:
+ (Class)getParserClass {
return [NCCurrencyParser class];
}
NCCurrencyParser.m:
NCCurrencyParser.m:
@interface NCCurrencyParser NSObject <NCParser>
@protocol NCParser
+(NSNumber *)parserNumber:(NSNumber *)number;
在调用方方法中:
Class parserClass = [Application getParserClass];
[parserClass parserNumber:1.0];
但是随后编译器给我一个错误,即parserClass可能不响应parseNumber.我如何强制Class必须采用某些协议,例如: Class< NCParser>
(但不起作用)
But then the compiler gives me the error that parserClass may not respond to parseNumber. How can I force the Class have to adopt to some protocol like : Class <NCParser>
(but it doesn't work)
推荐答案
Class 对象是第一类对象,并且可以实现任何其他协议Objective-C对象(id,NSObject *,...)
Class objects in Objective-C are first class objects, and can can implement protocols like any other Objective-C object (id, NSObject*, ...)
因此,只要对其他Object协议执行通常的操作即可,即:
So just do whatever you would normally do for any other Object protocol, ie:
+ (Class<NCParser>)getParserClass {
return [NCCurrencyParser class];
}
还有
Class<NCParser> parserClass = [Application getParserClass];
[parserClass parserNumber:1.0];
在xcode 3.2.3,iPhone Simulator 4.0,GCC 4.2上构建/编译/测试
这篇关于iPhone如何指定Class数据类型必须采用的协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!