Return copy or mutable object

Which option is more correct?

//first variant
    - (NSArray*) someArray
    {
     NSMutableArray* mutArr = [[NSMutableArray alloc] init];

     //...some operations with mutArr


     NSArray* retArray = [mutArr copy];

     [mutArr release]; //remove mutArr

     return [retArray autorelease];
    }

//second variant
    - (NSArray*) someArray
    {
     NSMutableArray* mutArr = [[NSMutableArray alloc] init];

     //...some operations with mutArr 

     return (NSArray*)[mutArr autorelease];
    }
+3
source share
3 answers

Answer: how many problems will there be if the array is changed after it is returned?

If you create a mutable array inside your method and then return it, never use it again, I think it is ok to return a mutable version. The fact that your method declares an NSArray return type means that you cannot guarantee that the array will change. You must not guarantee that it is immutable.

On the other hand, if you return an array that your class uses internally, it is much safer to return an immutable copy. In the above example, this does not seem to be the case.

, , copy retain; , . , . , .

, . ( (NSArray *) .)

+6

, , . .

+1

, mutArr names . , , .

mutArray, ; NSMutableArray NSArray, . , NSArray, :

(NSArray*)someArray {
    NSMutableArray* mutArr = [[[NSMutableArray alloc] init ] autorelease];
    // your operations here
    return [NSArray arrayWithArray:mutArr];
}
+1

Source: https://habr.com/ru/post/1728700/


All Articles