Objective-C是否支持泛型? [英] Does Objective-C support Generics?
问题描述
我不知道Objective-C是否提供了对泛型的支持?
例如,考虑一个方法:
- (void)sort:(NSMutableArray *)deck {
}
我有什么办法让它只处理卡牌?
这样的东西是否可以执行?
- (void)sort:(NSMutableArray< Card *>)deck {
}
您可以使用 introspection工具。
基本上,它意味着您可以检查数组中的所有对象是否都是种类(类A或其一个子类)或 (A类),或者如果对象符合协议或响应选择器(存在某种方法)。
- (void)sort:(NSMutableArray *)deck {
for(id obj in deck){
if(obj isKindOfClass :[A class]]){
//这是正确的类
}
}
}
您可以在 NSArray
上编写一个Category方法,用于在每个对象上检查此方法。
BOOL allAreKindOfA = [array allObjectsAreKindOfClass:[A class]];
通常你实际上不需要这么多,因为你知道你放在一个集合中。
如果您需要检查数组中对象的类型或能力,这可能是一个指标,表明您的架构已损坏 / p>
另一个选项可以是 NSMutableArray
的子类,类。但请注意 NSMutableArray 和 NSArray ,因为这些是类集群,因此不容易子类化。
请注意:在我的其他answer 我创建了一个 NSMutableArray
子类,它使用一个块来测试,如果满足某个要求。如果你测试类成员资格,这将完全按照你想要的。使用第二个块进行错误处理。
I wonder whether Objective-C offers any support for generics?
For instance, consider a method:
-(void) sort: (NSMutableArray *) deck {
}
Is there any way for me to make it only deal with Deck of Cards?
Is something like this possible to enforce?
-(void) sort: (NSMutableArray <Card *>) deck {
}
You can use the introspection tools offered by the objective-c runtime.
Basically, it means you can check if all objects in an array either are a kind of class (Class A or one subclass of it) or a member of class (class A), or if a objects conforms to a protocol or responds to a selector (a certain method is present).
-(void) sort: (NSMutableArray *) deck {
for(id obj in deck){
if(obj isKindOfClass:[A class]]){
//this is of right class
}
}
}
You could write a Category method on NSArray
that checkouts this on every object.
BOOL allAreKindOfA = [array allObjectsAreKindOfClass:[A class]];
Normally you actually don't need this very often, as you know what you put inside a collection.
If you need to check the type or ability of an object in a Array, this might be an indicator, that your Architecture is broken
Another option could be a subclass of NSMutableArray
that only accepts certain classes. But be aware of the subclassing notes for NSMutableArray and NSArray, as these are Class-Clusters and therefore not easy to subclass.
Note: In my other answer I created a NSMutableArray
subclass, that uses a block to test, if a certain requirement is fulfilled. If you test against class-membership, this will do exactly what you want. Use the second block for error handling.
这篇关于Objective-C是否支持泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!