NSString為什么用copy不用strong


我們大部分的時候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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM