Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray arrayWithArray compares same as NSArray mutableCopy?

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

NSArray *originalArray = @[obj1, obj2, oj3];

NSMutableArray *newMutableArray = nil;

if (thereIsSomeDifference) {  
    newMutableArray = [NSMutableArray arrayWithArray:originalArray];  
}  
else {  
    newMutableArray = [originalArray mutableCopy];  
} 
like image 321
seeker12 Avatar asked Jan 06 '13 20:01

seeker12


4 Answers

NO !!! There is two differences between these initializations :

  1. Retain count: in the first case, you get an autoreleased object, in the second case, you get a retained object, you will need to release it after (This doesn't apply on ARC)

  2. If originalArray is nil, in the first case, you will get a mutable array with 0 item, in the second case, you will get nil (because sending a message to nil returns nil). In your example, it is clear that originalArray is not nil but in real life you can reach this case (I just had the case)

like image 179
Johnmph Avatar answered Nov 13 '22 21:11

Johnmph


An array is equal to another array (isEqualToArray: selector) if they have the same objects (in the same order). This is verified using the isEqual: method (disregarding of the array being mutable or not).

They're just the same, one or another initialisation doesn't make any difference. Verify this logging the result of isEqualToArray: .

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

Notice that the comparison would be true even if you compared it with a non-mutable copy.

like image 28
Ramy Al Zuhouri Avatar answered Nov 13 '22 23:11

Ramy Al Zuhouri


No, the result of them is exactly the same.
Only the initialisation is different

like image 30
IluTov Avatar answered Nov 13 '22 21:11

IluTov


In order to answer, we have to define "sameness". The two inits side by side will result in different collections, but they will be the same insofar as 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]);
       }
   }
}
like image 40
danh Avatar answered Nov 13 '22 22:11

danh