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

  • 相关阅读:
    C#生成静态两方法
    ASP.NET C# 生成静态页面简单方法
    sql日期格式化
    Div+Css+JS做多个显示/隐藏内容块
    Request获取url各种信息的方法
    asp.net遍历页面所有的按钮(或控件)
    Donews.com:SpyMac.com也提供了1G的Email.
    再见 Swagger UI!国人开源了一款超好用的 API 文档生成框架,Star 4.7K+,真香!!
    面试官:new Object[5] 一共创建了几个对象?
    面试官:select......for update 会锁表还是锁行?别答错了!
  • 原文地址:https://www.cnblogs.com/sunyaxue/p/9651419.html
Copyright © 2011-2022 走看看