Best Practices for NSMutableArray Method Arguments

Asked 2 years ago, Updated 2 years ago, 89 views

What is the best method for NSMutableArray method arguments?
Array1 and array2 in the source code below contain similar values.

-(void)testMethod{

    NSMutableArray*array1 = NSMutableArray array;
    NSMutableArray*array2 = NSMutableArray array;
    [self testMethod01:array1];
    array2 = [self testMethod02];
}

-(void)testMethod01:(NSMutableArray*)aArray{

    [aArray addObject:@"test";
}

- (NSMutableArray*) testMethod02 {

    return@[@"test".mutableCopy;
}

So I have a question.
·Is it okay to write directly to the argument as objective-c like testMethod01?
·If it is OK to do the above, which is better, writing directly into the argument or getting it as a return value?

Please let me know if this is a small question.

That's all, thank you.

ios objective-c

2022-09-30 20:47

2 Answers

The assumption of your question is that testMethod01 and testMethod02 lead to the same results, but if you look a little closer, the results will not be the same.

NSMutableArray*array01 = [NSMutableArrayarrayWithObjects:@"Apple", @"Banana", @"Candy", nil ];
[self testMethod01:array01];

Output: {Apple, Banana, Candy, test}

NSMutableArray*array02 = [NSMutableArrayarrayWithObjects:@"Apple", @"Banana", @"Candy", nil ];
array02 = [self testMethod02];

Output: {test}

Therefore, it is not a comparison of "Which is better".

·Is it okay to write directly to the argument as objective-c like testMethod01?

Objective-C is an extension of the C language.The grammar and techniques of C language can be used in Objective-C.Everyone learns how to pass object references (pointers) to function arguments as the basis of the C language.Remember that the entity of the Objective-C method is a function of the C language.From the above, there is no room to conclude that it should not be used.


2022-09-30 20:47

I think there is no problem with either method.
I think it would be better to choose the one who can write beautifully on a case-by-case basis.

Personally, I prefer Method 2 type for the following reasons:
·I have the impression that Apple methods such as Cocoa return more new instances generated in the method than directly modifying the instances received by the arguments.
·From the caller's point of view, it is difficult to tell whether the method modifies the argument or not.


2022-09-30 20:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.