When the NSMutableString value changes after writing to an array, the values ​​in the array change as well, should it be? Or how to explain its change?

Here is the code for an example:

NSMutableArray *names = [[NSMutableArray alloc] initWithCapacity:10]; NSMutableString *name = [[NSMutableString alloc] init]; [name setString:@"Alice"]; names[0] = name; NSLog(@"%@",names); [name setString:@"0"]; NSLog(@"%@",names); 

Here is the output of the program:

 Alice 0 

Although it should be:

 Alice Alice 

When replacing NSMutableString with NSString, outputs as necessary

  • With NSMuatableString, you can perform various operations: change, add text, etc., and NSString can not be changed. - Orest Mykha

1 answer 1

Well, I'll try.

In the first case: you assign your string value. Since this is a pointer, it points to some kind of memory area (say, 0x1, which contains the text 'Alice'). After that, you assign the same value to the array (again, the first element of the array indicates 0x1 - 'Alice'). then you change the value of the string, and since the string is mutable, it mutates and the new value '0' is written to 0x1. Due to the fact that the first element of the array still points to 0x1, it turns out that there is also a new value.

The second case (replacing with non-mutable NSString): the beginning is the same - the string indicates 0x1 'Alice' and the array is also there. when you change the value of a string, it does not mutate, but is written to a new memory area (for example, 0x2 - '0'), the string contains what is in 0x2, and the array still points to 0x1.