Return mutable or copy
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.
精彩评论