Does NSMutableArray arrayWithArray compare the same as mutableCopy NSArray?

Given the following code example, is the newMutableArrray variable different depending on two different initializations or the same?

 NSArray *originalArray = @[obj1, obj2, oj3]; NSMutableArray *newMutableArray = nil; if (thereIsSomeDifference) { newMutableArray = [NSMutableArray arrayWithArray:originalArray]; } else { newMutableArray = [originalArray mutableCopy]; } 
+7
source share
4 answers

An array is equal to another array (isEqualToArray: selector) if they have the same objects (in the same order). This is checked using the isEqual: method (regardless of the variable array or not).

They are the same, one or the other initialization does not matter. Make sure this is the result of registering isEqualToArray :.

 NSArray *originalArray = @[obj1, obj2, oj3]; NSMutableArray *newMutableArray = nil; newMutableArray = [NSMutableArray arrayWithArray:originalArray]; thereIsSomeDifference= ![newMutableArray isEqualToArray: [originArray mutableCopy] ]; 

Note that the comparison will be true even if you compare it with a non-volatile copy.

+6
source

NOT!!! There are two differences between these initializations:

  • Keep counter: in the first case you get an object with auto-implementation, in the second case you get a saved object, you need to free it after (this does not apply to ARC)

  • If originalArray is zero, in the first case you get a mutable array with 0 element, in the second case you get zero (because sending a message to nil returns zero). In your example, it is clear that originalArray is not zero, but in real life you can achieve this case (I just dealt)

+15
source

No, their result is exactly the same.
Only initialization is different

+1
source

To answer, we must define "sameness." These two sides will have different collections side by side, but they will be the same if they point to the same elements.

In other words:

 initA = [NSMutableArray arrayWithArray:originalArray]; initB = [originalArray mutableCopy]; if (initA == initB) { // unreachable, because the pointers differ } // however if ([initA isEqualToArray:initB]) { // will be true // because for (int i=0; i<initA.count; i++) { if ([initA objectAtIndex:i] == [initB objectAtIndex:i]) { NSLog(@"this will log every element %@ in the arrays", [initA objectAtIndex:i]); } } } 
+1
source

All Articles