views:

34

answers:

1

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 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
}
+1  A: 

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.

Jasarien
I remember this being asked before; I think in general it’s ok to return the mutable array straight up from methods like that which simply create and return the array (since your object isn’t retaining it itself and doesn’t care if the contents change or not). If you were returning an ivar, you’d definitely want to copy/autorelease it on return.If your method says it returns an `NSArray*`, callers should treat it as if it was immutable, even if it isn’t (though I’m sure sometimes this doesn’t happen).
Wevah