0

如何引用实现特定协议的类(不是它的实例!)?

+(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
}

WhereDataDataManger是协议,SpecializedDataManager是实现DataManager协议的类。

4

3 回答 3

0

我自己没有尝试过,但是您应该能够使用指向类的指针,尽管我怀疑您是否可以指定该类必须实现某个协议:

static Class manager = NULL;

+ (void)someInitMethod
{
    manager = [SpecializedDataManager class];
    NSAssert([manager conformsToProtocol:@protocol(DataManager)], @"Achtung!"); 
}
于 2012-06-01T12:37:35.467 回答
0

这是你要找的:

+(id<Data>) dataForName:(NSString *)name {
    Class<DataManager> manager = [SpecializedDataManager class];
    return [[manager sharedManager] get:name];
}
于 2012-07-18T20:47:43.987 回答
0

如果我理解你是正确的,你想写这样的东西:

id<SomeProtocol> someObject = AnotherObjectConformingThisProtocol;    
Class class = [(NSObject*)SomeObject class];

if ([someObject isKindOfClass:[AnotherObjectConformingThisProtocol class]]) {}
if (class == [AnotherObjectConformingSomeProtocol class]) {}

如果不是 - 请澄清你的意思。

更新:我在另一篇文章附近阅读了您的评论并得到了它:

为您的 DataManager 和 Data 协议创建包装类:

@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
}
于 2012-06-01T12:49:46.230 回答