iphone how to specify the Class data type have to adopt to a protocol

☆樱花仙子☆ 提交于 2019-12-11 04:37:31

问题


In my application, I need to return the "Class" as a return type like:

Application.m:

+ (Class)getParserClass {
  return [NCCurrencyParser class];
}

NCCurrencyParser.m:

@interface NCCurrencyParser NSObject <NCParser>
@protocol NCParser
  +(NSNumber *)parserNumber:(NSNumber *)number;

in the caller method:

Class parserClass = [Application getParserClass];
[parserClass parserNumber:1.0];

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)


回答1:


Class objects in Objective-C are first class objects, and can can implement protocols like any other Objective-C object (id, NSObject*, ...)

So just do whatever you would normally do for any other Object protocol, ie:

+ (Class<NCParser>)getParserClass {
  return [NCCurrencyParser class];
}

And

Class<NCParser> parserClass = [Application getParserClass];
[parserClass parserNumber:1.0];

Build/Compiled/Tested on xcode 3.2.3, iPhone Simulator 4.0, GCC 4.2




回答2:


What is going on...this just seems VERY wrong.

But doing Class<NCParser> parserClass = [Application getParserClass]; should work




回答3:


"But then the compiler gives me the error that parserClass may not respond to parseNumber"

If you just need to ignore the error message. Put this in the class which has the caller method:

#import "NCParser.h"

will solve your problem. It just works!

I think XCode bases on your import to determine the methods for Class.

"How can I force the Class have to adopt to some protocol like : Class"

You can check a NCObject or id conform to a protocol at compile time using id <AProtocol>. But I don't think you can do that for a Class object.

My approach is check it in runtime. Like this:

NSObject *object = [[class alloc] init];
NSAssert ([object conformsToProtocol:@protocol(AProtocol)], 
          @"`class` should conform AProtocol");


来源:https://stackoverflow.com/questions/3278442/iphone-how-to-specify-the-class-data-type-have-to-adopt-to-a-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!