刚学习oc,发现一个很难理解的问题
假设我在某一个类里面定义如下几个实例属性
@property (nonatomic, strong) NSString *strongString;
@property (nonatomic, strong) NSMutableString *strongMutableString;
@property (nonatomic, copy) NSString *copyedString;
@property (nonatomic, copy) NSMutableString *copyedMutableString;
调用实例方法,实现的功能如下,就是简单的赋值
-
将不可变字符串赋值给属性
NSString *string = [NSString stringWithFormat:@"abc"]; self.strongString = string; self.strongMutableString = string; self.copyedMutableString = string; self.copyedString = string; string = [string stringByAppendingString:@"123"]; // 打印输出实例属性的地址 NSLog(@"\n origin string: %p, %p %@", string, &string, string); NSLog(@"\n strong string: %p, %p %@", _strongString, &_strongString, _strongString); NSLog(@"\n strongMutable string: %p, %p %@", _strongMutableString, &_strongMutableString, _strongMutableString); NSLog(@"\n copy string: %p, %p %@", _copyedString, &_copyedString, _copyedString); NSLog(@"\n copyMutable: %p, %p %@", _copyedMutableString, &_copyedMutableString, _copyedMutableString);
输出如下
origin string: 0x100534da0, 0x7ffeefbff4c8 abc123 strong string: 0x21bd4156d4fa7111, 0x100534c88 abc strongMutable string: 0x21bd4156d4fa7111, 0x100534c90 abc copy string: 0x21bd4156d4fa7111, 0x100534c98 abc copyMutable: 0x21bd4156d4fa7111, 0x100534ca0 abc
这个大概能理解 都是浅拷贝 地址没有变化
-
然而将可变字符串赋值给属性时,我就搞不懂了
NSMutableString *multableString = [NSMutableString stringWithFormat:@"def"]; self.strongString = multableString; self.strongMutableString = multableString; self.copyedMutableString = multableString; self.copyedString = multableString; [multableString appendString:@"123"]; // 打印输出实例属性的地址 NSLog(@"\n origin string: %p, %p %@", multableString, &multableString, multableString); NSLog(@"\n strong string: %p, %p %@", _strongString, &_strongString, _strongString); NSLog(@"\n strongMutable string: %p, %p %@", _strongMutableString, &_strongMutableString, _strongMutableString); NSLog(@"\n copy string: %p, %p %@", _copyedString, &_copyedString, _copyedString); NSLog(@"\n copyMutable: %p, %p %@", _copyedMutableString, &_copyedMutableString, _copyedMutableString);
输出结果
origin string: 0x100651af0, 0x7ffeefbff4c8 def123 strong string: 0x100651af0, 0x100651a28 def123 strongMutable string: 0x100651af0, 0x100651a30 def123 copy string: 0x64fd82cbad71056f, 0x100651a38 def copyMutable: 0x64fd82cbad71056f, 0x100651a40 def
用
strong
修饰的属性是浅拷贝,地址一样我能理解但是!!为什么copy的属性,地址是一样的????
浅拷贝和深拷贝的理解
copy 相对于指针复制,内存地址一致的