zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    jQuery插件之jqzoom
    python数据分析画图体验
    python正则表达式,以及应用[下载图片]
    Python 程序如何高效地调试?
    从汉诺塔游戏理解python递归函数
    Python文本文件的输入输出操作学习
    Windows搭建python开发环境
    python循环综合运用
    Python参数传递,既不是传值也不是传引用
    使用python实现用微信远程控制电脑
  • 原文地址:https://www.cnblogs.com/sunyaxue/p/9651419.html
Copyright © 2011-2022 走看看