是否可以从使用instancetype的类构造函数中返回子类? [英] Is it okay to return a subclass from a class constructor that uses instancetype?
问题描述
我有一个类中的类方法构建一个Cocoa集合在某些方式,内置的初始化器不允许。由于初始化器功能有限,我必须使用可变版本的集合来实际构建它。下面是 NS {Mutable} IndexSet
的示例:
I have a class method in a category to construct a Cocoa collection in some way that the built-in initializers don't allow. Due to the limited initializer functionality, I have to use the mutable version of the collection to actually build it. Here's an example for NS{Mutable}IndexSet
:
@implementation NSIndexSet (WSSNonContiguous)
+ (instancetype)WSSIndexSetFromMask:(NSUInteger)mask
{
NSMutableIndexSet * set = [NSMutableIndexSet indexSet];
for( NSUInteger i = 0; i < (sizeof(NSUInteger) * 8); i++ ){
if( mask & (1l << i) ){
[set addIndex:i];
}
}
return set;
}
我的回报类型有时是谎言,
My return type is sometimes a lie here -- there's always a mutable collection being returned, whether the user is requesting an immutable version or not.
仍然适合使用 instancetype code>在这样的情况下,或者我应该与
id
?如果我使用 instancetype
,我也应该明确地重新创建集合:
Is it still appropriate to use instancetype
in cases like this, or should I go with id
? If I do use instancetype
, should I also be explicitly re-creating the collection:
// Ick?
return [[self alloc] initWithIndexSet:set];
以确保在调用 + [NSIndexSet]时返回不可变拷贝WSSIndexSetFromMask:]
?
推荐答案
一切正常:
NSIndexSet *set = [[NSIndexSet WSSIndexSetFromMask:0] addIndex:0];
No visible @interface for 'NSIndexSet' declares the selector 'addIndex:'
instancetype
对发件人说,返回一个接收者类型的实例,即使它是一个子类型。对于发送者,它是一个NSIndexSet,因为它被发送到NSIndexSet的类对象。
instancetype
says to the sender, that you return a instance of the receivers type even it is a subtype. For the sender it is a NSIndexSet, because it is send to the class object of NSIndexSet.
这种自省,有人期待返回类型并看到一个子类并利用这些信息的任何优势,格式不正确。合同是用返回类型构建的,在这种情况下是NSIndexSet。
An introspection that way, that someone looks to the return type and sees a subclass and takes any advantage out of this information, is malformed. The contract is build with the return type and this is in this case NSIndexSet.
这篇关于是否可以从使用instancetype的类构造函数中返回子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!