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];
}
NO !!! There is two differences between these initializations :
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)
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)
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.
No, the result of them is exactly the same.
Only the initialisation is different
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]);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With