• 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

  • 相关阅读:
    使用气泡图分析产品价格变动带来的影响
    如果数据太“ 脏 ”,你知道如何处理吗?
    Power BI文件夹管理,99%的人都不知道的技巧
    如果数据太“ 脏 ”,你知道如何处理吗?
    Power BI文件夹管理,99%的人都不知道的技巧
    微软Power BI 每月功能更新系列——Power BI 3月版本功能更新新鲜出炉
    textarea右下角黑点
    CSS布局-body高度不等于页面高度
    PS切图采坑
    诡异的bug!!
  • 原文地址:https://www.cnblogs.com/sunyaxue/p/9651419.html
Copyright © 2020-2023  润新知