簡體   English   中英

Objective C 協議泛型

[英]Objective c protocol generics

Objective-C 協議可以通用嗎?

按照本教程,我基本上是在尋找類似的東西:

@protocol ItemsStore<__covariant ObjectType> <NSObject>

-(NSArray <ObjectType> *)items;

@end

這是某些ObjectType的通用協議,它“實現”(“繼承”)另一個協議NSObject

正如@rmaddy 所建議的那樣,正如提到的這個問題,這是不可能的。 恥辱,然后轉向斯威夫特......

也許您可以在界面中將其重新定義為泛型。

@protocol ItemsStore <NSObject>

- (NSArray *)items;

@end

@interface MyItemsStore<ObjectType> : NSObject <ItemsStore>

- (NSArray <ObjectType> *)items;

@end

不過,這似乎不太可能發生。 您最好只定義每個子類中的項目類型。 就像 Apple 在其核心數據模型生成中對NSFetchRequest所做的一樣。

可能,這個問題與我的來源問題完全相同。 嗯,設計的想法很棒,但不適用於 ObjC。 我也想知道這個。 我認為它可以像這樣工作:

@protocol Prototype<__covariant OtherProtocolOrClass> <NSObject>
/// Construct an object of the desired class or protocol
@property (nonatomic, nonnull, readonly) <OtherProtocolOrClass> objectFromPrototype;
@end

(我還沒有測試過@protocol Prototype <NSObject,__covariant OtherProtocolOrClass> ,但我認為它會失敗。)

我框架中的另一個對象(它是一個集合)指出,如果有一個返回實例的 Prototype,它可以自動構造一個對象類型的NSArray<ObjectType>* ,如下所示:

@interface ValueProto : NSObject <Prototype<id<Value>>>
@end

@implementation ValueProto
-(id<Value>)objectFromPrototype {
    return [Value new];
}
@end

我的夢想,這個系列是這樣構建的:

MyCollection<id<Value>>* const collection = [MyCollection new];
collection.prototype = [ValuesProto new];

如果您隨后訪問集合的屬性,則會動態構造id<Value>對象數組:

-(NSArray<id<Value>>*)values {
    NSArray*const sourceCollection = ...
    NSMutableArray<id<Value>>* const result = [NSMutableArray arrayWithCapacity:sourceCollection.count];
    for (id o in sourceCollection) {
        id<Value> v = self.prototype.objectFromPrototype;
        v.content = o;
        [result addObject:v];
    }
    return result;
}

相反,我的類的對象之一必須是原型本身:

-(id)objectFromPrototype {
    return [self.class new];
}

這與我所謂的“注入器”相沖突,后者通過協議而不是類來構造和返回對象。

如果任何 Apple 工程師正在閱讀本文:

請為 ObjC 提供協議協變。 還沒死呢! :-)

為什么不使用泛型抽象類?

@interface AbstractItemStore <__covariant ObjectType> : NSObject

- (NSArray<ObjectType> *)items;

@end

@implementation AbstractItemStore

- (NSArray<id> *)items {
    NSParameterAssert("Not implemented!");
    return nil;
}

@end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM