Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning, mutable to immutable array?

Would someone be so kind as to confirm that I am understanding this correctly. My initial response to this was that the mutableArray when assigned to an immutableArray would become an immutableArray, however this is not the case.

Is this because the initial array is allocated as a mutableArray and the immutableArray is just assigned to point to the same object. The compiler gives a warning, but the the code executes just fine at runtime.

NSMutableArray *mArray = [NSMutableArray arrayWithObjects:@"Teddy", @"Dog", nil];
NSArray *iArray = mArray;
[iArray addObject:@"Snoss"]; // Normally this would crash NSArray

much appreciated

gary.

like image 980
fuzzygoat Avatar asked Feb 26 '23 22:02

fuzzygoat


1 Answers

Don't confuse the physical object that you just created, with how you are effectivley casting it in your code.

In this case, you did physically create a NSMutableArray.

Then you effectivley cast it to an NSArray - which is totally valid - for example, there are many cases where a function might want an NSArray, and you can pass it an NSArray, or anything derived from it (like an NSMutableArray).

The problem is that you get a compiler warning because you are trying to call addObject on an object which the compiler thinks is just an NSArray because that's what it's physical type is.

This will actually work, because it actually is an NSMutableArray, and in runtime would respond to that selector.

It's bad coding practice to do it this way, because NSArray doesn't actualy respond to the addObject selector. For example, I could create a function, like:

-(void) addIt:(NSArray)myThing {
  [myThing addObject:@"New String"];
}

The compiler would give you a warning saying the "NSArray" doesn't respond to the "addObject" selector. If you cast an NSMutableArray, and passed it to this function, it myThing, it would actually work.

It's bad practice though, because if you actually passed an NSArray it would crash.

Summary: Don't confuse what the object really is vs. what you are making the compiler interpret it as.

like image 103
Brad Avatar answered Mar 03 '23 23:03

Brad