可变属性用strong,不可变属性用copy
当源字符串是NSMutableString时,strong属性只是增加了源字符串的引用计数,而copy属性则是对源字符串做了次深拷贝,产生一个新的对象,且copy属性对象指向这个新的对象。另外需要注意的是,这个copy属性对象的类型始终是NSString,而不是NSMutableString,因此其是不可变的。
什么叫做浅拷贝,什么叫做深拷贝;
- 浅Copy:可以理解为指针的复制,只是多了一个指向这块内存的指针,共用一块内存。
- 深Copy:理解为内存的复制,两块内存是完全不同的,也就是两个对象指针分别指向不同的内存,互不干涉。
@property (nonatomic, strong) NSString *stringStrong; //strong修饰的字符串对象
@property (nonatomic, copy) NSString *stringCopy; //copy修饰的字符串对象
NSString *strong = @"StrongStr!";
NSString *copy = @"CopyStr!";
self.stringStrong = strong;
self.stringCopy = copy;
NSLog(@"strong = %p",strong);
NSLog(@"stringStrong = %p",self.stringStrong);
NSLog(@"copy = %p",copy);
NSLog(@"stringCopy = %p",self.stringCopy);
tesssss[2308:776694] strong = 0x100345458
tesssss[2308:776694] stringStrong = 0x100345458
tesssss[2308:776694] copy = 0x100345478
tesssss[2308:776694] stringCopy = 0x100345478
用NSString给strong修饰的NSString 与
用copy修饰的NSString的结果一样,最后都是拷贝了地址。
现在用两个NSMutableString去给NSString赋值
@property (nonatomic, strong) NSString *stringStrong; //strong修饰的字符串对象
@property (nonatomic, copy) NSString *stringCopy; //copy修饰的字符串对象
NSMutableString *mutableStrong = [NSMutableString stringWithString:@"StrongMutableStr"];
NSMutableString *mutableCopy = [NSMutableString stringWithString:@"CopyMutableStr"];
self.stringStrong = mutableStrong;
self.stringCopy = mutableCopy;
NSLog(@"mutableStrong = %p",mutableStrong);
NSLog(@"stringStrong = %p",self.stringStrong);
NSLog(@"================");
NSLog(@"mutableCopy = %p",mutableCopy);
NSLog(@"stringCopy = %p",self.stringCopy);
tesssss[2312:777063] mutableStrong = 0x174070700
tesssss[2312:777063] stringStrong = 0x174070700
tesssss[2312:777063] ================
tesssss[2312:777063] mutableCopy = 0x174070740
tesssss[2312:777063] stringCopy = 0x174023340
用NSMutableString给strong修饰的NSString赋值,可见是复制了地址,引用计数加一。
用NSMutableString给copy修饰的NSString赋值,可见是复制了内容,两块地址不同
接下来修改NSMutableString的值
[mutableStrong appendString:@"Append Strong!"];
[mutableCopy appendString:@"Append Copy!"];
NSLog(@"mutableStrong = %@",mutableStrong);
NSLog(@"stringStrong = %@",self.stringStrong);
NSLog(@"================");
NSLog(@"mutableCopy = %@",mutableCopy);
NSLog(@"stringCopy = %@",self.stringCopy);
tesssss[2317:777820] mutableStrong = StrongMutableStrAppend Strong!
tesssss[2317:777820] stringStrong = StrongMutableStrAppend Strong!
tesssss[2317:777820] ================
tesssss[2317:777820] mutableCopy = CopyMutableStrAppend Copy!
tesssss[2317:777820] stringCopy = CopyMutableStr
strong修饰的NSString拷贝的是指针,指向的是同一片内存,所以当指针指向的地址的内容改变了之后,对应的值也被修改了。