我們大部分的時候NSString的屬性都是copy,那copy與strong的情況下到底有什么區別呢?我們以實例來說明:
@property(strong, nonatomic) NSString *strongStr;
@property(copy, nonatomic) NSString *copStr;
NSString *str = [NSString stringWithFormat:@"lihu"];; self.strongStr = str; self.copStr = str; NSLog(@"strongStr--%@, %p", self.strongStr, self.strongStr); NSLog(@"copStr--%@, %p", self.copStr, self.copStr); NSLog(@"str--%@, %p", str, str);
2018-09-15 16:50:56.151846+0800 youxiang[59724:1435155] strongStr--lihu, 0xa0000007568696c4
2018-09-15 16:50:56.151940+0800 youxiang[59724:1435155] copStr--lihu, 0xa0000007568696c4
2018-09-15 16:50:56.152079+0800 youxiang[59724:1435155] str--lihu, 0xa0000007568696c4
如果用NSString賦值的話strong和copy(此刻是淺拷貝)是沒有區別的
NSMutableString *str1=[NSMutableString stringWithFormat:@"helloworld"]; self.strongStr=str1; self.copStr=str1; NSLog(@"可變strongStr--%@, %p", self.strongStr, self.strongStr); NSLog(@"可變copStr--%@, %p", self.copStr, self.copStr); NSLog(@"可變str--%@, %p", str1, str1); [str1 appendString:@"hry"]; NSLog(@"********strongStr********%@",self.strongStr); NSLog(@"********copStr********%@",self.copStr);
2018-09-15 16:53:16.969865+0800 youxiang[59798:1436931] 可變strongStr--helloworld, 0x60400024a7d0
2018-09-15 16:53:16.969971+0800 youxiang[59798:1436931] 可變copStr--helloworld, 0x6040000362c0
2018-09-15 16:53:16.970417+0800 youxiang[59798:1436931] 可變str--helloworld, 0x60400024a7d0
2018-09-15 16:53:16.970770+0800 youxiang[59798:1436931] ********strongStr********helloworldhry
2018-09-15 16:53:16.970865+0800 youxiang[59798:1436931] ********copStr********helloworld
如果用NSMutableString賦值的話strong沒有只是增加了str1的計數器,並沒有開辟新的內存
copy的話開辟了新的內存,對str1的內容進行修改的話,strong的字符串內容改變了,而copy的並沒有改變
如果需要改變的話可以用strong,如果不需要改變的話用copy