Copied or saved AddObject in NSMutableArray?

When you add an object to a collection, for example NSMutableArray, the object is copied, i.e. semantics of meaning or persisted, that is, referential semantics?

I am confused in the example:

NSMutableString *testStr = [@"test" mutableCopy];
NSMutableArray *arrayA = [[NSMutableArray alloc] init];

[arrayA addObject:testStr];
NSLog(@"%@", arrayA);    // output: test

testStr = [@"world" mutableCopy];
NSLog(@"%@", arrayA);    // output: test

// testStr is copied - value semantics

NSMutableArray *testArr = [@[@1, @2] mutableCopy];
NSMutableArray *arrarB = [[NSMutableArray alloc] init];

[arrarB addObject:testArr];
NSLog(@"%@", arrarB);      // output: [1, 2]

[testArr addObject:@3];
NSLog(@"%@", arrarB);      // output: [1, 2, 3]

// testArr is retained - reference semantics

You can see: if the object is NSMutableString, it looks like a copied object - you change the object, it will not affect the object in the array.

However, if the object is NSMutableArray, when the object is changed, the object in the array also changes - for example, you save the object or pass by reference.

Am I missing something? Thanks.

+4
source share
4 answers

, , , .

+3

. :

NSMutableString NSMutableArray:

NSMutableString *testStr = [@"test" mutableCopy];
NSMutableArray *arrayA = [[NSMutableArray alloc] init];

:

[arrayA addObject:testStr];
NSLog(@"%@", arrayA);    // output: test

NSMutableString testStr, testStr . :

testStr = [@"world" mutableCopy];
NSLog(@"%@", arrayA);    // output: test

, , .

, , , , , , testArr , arrarB, arrarB , testArr.

+3

:

testStr = [@"world" mutableCopy];

testStr,

+2
NSMutableString *testStr = [@"test" mutableCopy];
NSMutableArray *arrayA = [[NSMutableArray alloc] init];
[arrayA addObject:testStr];
NSLog(@"%@", arrayA);    // output: test

testStr = [@"world" mutableCopy];
NSLog(@"%@", arrayA);    // output: test

testStr arrayA. testStr , testStr - (, "" ).

At the same time, as for the array, you can also add another row to testStr (instead of pointing to another row), you can see the same results as testArr.

  [testStr appendString:@" Test 2"];
`NSLog(@"%@", arrayA);`    // output: test Test 2
-1
source

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


All Articles