开发者

Return mutable or copy

开发者 https://www.devze.com 2023-01-04 23:57 出处:网络
If you have a method in objective c that builds an array or dictionary using a mutable object, should you then copy the object, or return the mutable version? This开发者_StackOverflow is probably a ca

If you have a method in objective c that builds an array or dictionary using a mutable object, should you then copy the object, or return the mutable version? This开发者_StackOverflow is probably a case of opinion but I have never been able to make up my mind. Here are two examples to show what I am talking about:

- (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
}


It depends what the method will be used for, or what the intented use for the returned array is.

By convention it is considered normal to copy and autorelease the mutable array before returning it, thereby complying to the object ownership conventions and protecting the data from being changed once it's returned.

0

精彩评论

暂无评论...
验证码 换一张
取 消