Assignment, change to immutable array?

Someone will be so kind as to confirm that I understand this correctly. My initial answer to this was that mutableArray when assigned to an immutable array will become an immutable array, however this is not the case.

This is because the original array is allocated as mutableArray, and immutableArray is simply assigned to point to the same object. The compiler generates a warning, but the code runs fine at runtime.

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

much appreciated

Gary.

+3
source share
4 answers

Do not confuse the physical object you just created with how you insert it into your code.

NSMutableArray.

NSArray, , , , NSArray, NSArray -, (, NSMutableArray).

, , addObject , , , NSArray, .

, NSMutableArray, .

, NSArray addObject. , , :

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

, "NSArray" "addObject". NSMutableArray , myThing, .

, , NSArray, .

: , , , , .

+4

, .

NSArray *array = [NSArray arrayWithArray:mutableArray];

+2

iArray NSMutableArray, NSMutableArray.

Obj-c , 'id'.

NSNumber *iArray = mArray

( ). .

, , ++. ( ).

Obj-c , script/ . ( ), , .. - . C/++ .

+1

AFAIK, . NSMutableArray NSArray, mArray iArray .

, .

0

Source: https://habr.com/ru/post/1772911/


All Articles