-1

我在一个类别中有一个类方法来以某种内置初始化程序不允许的方式构造一个 Cocoa 集合。由于初始化程序功能有限,我必须使用集合的可变版本来实际构建它。这是一个示例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;
}

我的返回类型有时在这里是个谎言——无论用户是否请求不可变版本,总会返回一个可变集合。

在这种情况下使用它是否仍然合适instancetype,还是应该使用id?如果我确实使用instancetype,我是否也应该明确地重新创建集合:

// Ick?
return [[self alloc] initWithIndexSet:set];

确保在调用时返回不可变副本+[NSIndexSet WSSIndexSetFromMask:]

4

1 回答 1

2

一切正常:

NSIndexSet *set = [[NSIndexSet WSSIndexSetFromMask:0] addIndex:0];

No visible @interface for 'NSIndexSet' declares the selector 'addIndex:'

instancetype对发送者说,即使它是子类型,您也会返回接收者类型的实例。对于发送者它是一个 NSIndexSet,因为它被发送到 NSIndexSet 的类对象。

以这种方式进行的内省,即某人查看返回类型并查看子类并利用此信息的任何优势,是格式错误的。合约是使用返回类型构建的,在本例中为 NSIndexSet。

于 2013-05-25T21:32:17.590 回答