如何引用实现特定协议的类(不是它的实例!)?
+(id<Data>) dataForName:(NSString *)name {
id<DataManager> manager = SpecializedDataManager; // <-- which datatype does "manager" have to be?
return [[manager sharedManager] get:name]; //Getting data over a singleton of manager
}
其中Data
和DataManger
是协议,SpecializedDataManager
是实现DataManager
协议的类。
答案 0 :(得分:0)
我自己没有尝试过,但你应该能够使用指向类的指针,虽然我怀疑你可以指定该类必须实现某个协议:
static Class manager = NULL;
+ (void)someInitMethod
{
manager = [SpecializedDataManager class];
NSAssert([manager conformsToProtocol:@protocol(DataManager)], @"Achtung!");
}
答案 1 :(得分:0)
如果我理解你是对的,你想写这样的东西:
id<SomeProtocol> someObject = AnotherObjectConformingThisProtocol;
Class class = [(NSObject*)SomeObject class];
if ([someObject isKindOfClass:[AnotherObjectConformingThisProtocol class]]) {}
if (class == [AnotherObjectConformingSomeProtocol class]) {}
如果不是 - 请澄清你究竟是什么意思。
更新:我已经在另一篇文章附近阅读了你的评论并得到了它:
为您的DataManager和数据协议创建包装类:
@interface DataClass : NSObject <Data>
@end
@interface DataManagerClass : NSObject <DataManager>
@end
使用这样的代码:
+(DataClass*) dataForName:(NSString *)name {
DataManagerClass* manager = SpecializedDataManager; // <-- which datatype does "manager" have to be?
return [[manager sharedManager] get:name]; //Getting data over a singleton of manager
}
答案 2 :(得分:0)
这就是你要找的东西:
+(id<Data>) dataForName:(NSString *)name {
Class<DataManager> manager = [SpecializedDataManager class];
return [[manager sharedManager] get:name];
}