每个人都说您不能更改/修改 不可变 对象。我有不同的解释方式。您可以修改它,但是您将创建一个指向新对象的 new 指针,它不像您修改旧对象,它是一个品牌。新的。目的。任何具有先前指向它的指针的指针都不会看到它的变化。然而,如果它是一个可变对象,任何先前指向它的对象都会看到它的 new 值。请参阅示例。
仅供参考%p 打印堆中的指针位置。
NSString * A = @"Bob";
NSString * B = @"Bob";
NSString * C = @"Bob1";
NSString * D = A;
NSLog(@"\n %p for A \n %p for B \n %p for C \n %p for D",A,B,C,D);
// memory location of A,B,D are same.
0x104129068 代表 A
0x104129068 为 B
0x104129088 用于 C
0x104129068 为 D
修改指针A的对象
A = @"Bob2"; // this would create a new memory location for A, its previous memory location is still retained by B
NSLog(@"\n%p for A \n%p for B \n%p for C \n %p for D",A,B,C, D);
// A has a **new** memory location, B,D have same memory location.
0x1041290c8 用于 A
0x104129068 为 B
0x104129088 用于 C
0x104129068
为D
// NSMutableString * AA = @"Bob"; <-- you CAN'T do this you will get error: Incompatible pointer types initializing NSMutableString with an Expression of type NSString
NSMutableString * AA = [NSMutableString stringWithString:@"Bob1"];
NSString * BB = @"Bob";
NSString * CC = @"Bob1";
NSString * DD = AA;
NSLog(@"\n %p for AA \n %p for BB \n %p for CC \n %p for DD",AA,BB,CC,DD);
// memory location of AA,DD are same.
0x7ff26af14490 用于 AA
0x104129068 为 BB
0x104129088 为 CC
0x7ff26af14490 用于 DD
修改指针AA的对象
AA = (NSMutableString*)@"Bob3"; // This would NOT create a new memory location for A since its Mutable-- D was and still pointing to some location
NSLog(@"\n%p for AA \n%p for BB \n%p for CC \n %p for D",AA,BB,CC,DD);
// memory location of AA,DD are NOT same.
0x104129128 用于 AA
0x104129068 为 BB
0x104129088 为 CC
0x7ff26af14490 用于 DD
正如你想象的那样,所有 NSString 属性的默认存储属性是retain。有关copy 和retain 的更多信息,我强烈建议您阅读此问题。NSString property: copy or retain?