zoukankan      html  css  js  c++  java
  • ios开发之NSString用strong还是用copy?

    代码如下:

    1,声明

    @property(nonatomic,strong)NSString *firstName;
    
    @property(nonatomic,copy)NSString *secondName;

    2,代码

    NSMutableString *str1 = [NSMutableString stringWithFormat:@"李博"];
        self.firstName = str1;
        NSLog(@"使用strong第一次得到的名字:%@",self.firstName);
        
        [str1 appendString:@""];
        NSLog(@"使用strong第二次得到的名字:%@",self.firstName);
        
        NSMutableString *str2 = [NSMutableString stringWithFormat:@"李博"];
        self.secondName = str2;
        NSLog(@"使用copy第一次得到的名字:%@",self.secondName);
        
        [str2 appendString:@""];
        NSLog(@"使用copy第二次得到的名字:%@",self.secondName);

    3,打印

    2018-04-22 23:10:10.543151+0800 hgl-test[2709:61971] 使用strong第一次得到的名字:李博
    2018-04-22 23:10:10.543351+0800 hgl-test[2709:61971] 使用strong第二次得到的名字:李博爵
    2018-04-22 23:10:10.543503+0800 hgl-test[2709:61971] 使用copy第一次得到的名字:李博
    2018-04-22 23:10:10.543652+0800 hgl-test[2709:61971] 使用copy第二次得到的名字:李博

    从上面的例子我们可以看到:

    我们没有修改firstname的情况下,firstname却被修改了,就好像一个人的名字怎么能没有经过自己同意就被修改呢?我们的初衷是只想修改str1,但是firstname却被意外的修改了,而这就是我们使用strong所不想看到的,它会破坏程序的封装性。使用strong后firstname和str1只想的是同一片内容,所以修改其中一个值后两个值都变了

    反之,使用copy的话,str2通过copy得到一个新的对象赋值给secondname,这样我们再修改str2就跟secondname没有关系了,只有队secondname进行赋值才能改变它的值,这样就保证了程序的封装性。

    其实就是能更加深入理解深拷贝和浅拷贝的含义!

  • 相关阅读:
    Vue 2.x windows环境下安装
    VSCODE官网下载缓慢或下载失败 解决办法
    angular cli 降级
    Win10 VS2019 设置 以管理员身份运行
    XSHELL 连接 阿里云ECS实例
    Chrome浏览器跨域设置
    DBeaver 执行 mysql 多条语句报错
    DBeaver 连接MySql 8.0 报错 Public Key Retrieval is not allowed
    DBeaver 连接MySql 8.0报错 Unable to load authentication plugin 'caching_sha2_password'
    Linux系统分区
  • 原文地址:https://www.cnblogs.com/hero11223/p/8910729.html
Copyright © 2011-2022 走看看