返回可变或复制

时间:2010-06-26 00:28:02

标签: objective-c nsmutablearray

如果你在Objective c中有一个使用可变对象构建数组或字典的方法,那么你应该复制该对象,还是返回可变版本?这可能是一个意见,但我从来没有能够下定决心。这里有两个例子来说明我在说什么:

- (NSArray *)myMeth
{
    NSMutableArray *mutableArray = [NSMutableArray array];
    for (int i=0; i<10; i++) {
        [mutableArray addObject:[NSNumber numberWithInt:i]];
    }
    return mutableArray;//in order for calling code to modify this without warnings, it would have to cast it
}

- (NSArray *)myMeth
{
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    for (int i=0; i<10; i++) {
        [mutableArray addObject:[NSNumber numberWithInt:i]];
    }

    NSArray *array = [[mutableArray copy] autorelease];
    [mutableArray release];
    return array;//there is no way to modify this
}

1 个答案:

答案 0 :(得分:3)

这取决于方法将用于什么,或者返回数组的用途是什么。

按照惯例,在返回可变数组之前复制和自动释放它是正常的,从而遵守对象所有权约定并保护数据一旦返回就不会被更改。

相关问题