zoukankan      html  css  js  c++  java
  • NSString 使用 copy、strong

    // 首先定义2个属性
    @property (nonatomic, strong) NSString *stStr;
    @property (nonatomic, copy) NSString *coStr;
    
    // 测试
    - (void)_strong_copy {
        NSMutableString *mutableStr = [NSMutableString stringWithFormat:@"abc"];
        
        self.stStr = mutableStr;
        self.coStr = mutableStr;
        
        NSLog(@"mutableStr:%p, %p", mutableStr, &mutableStr);
        NSLog(@"strongStr :%p, %p", _stStr, &_stStr);
        NSLog(@"copyStr   :%p,%p", _coStr, &_coStr);
        
        NSLog(@"
    
    ");
        
        [mutableStr appendString:@"de"];
        NSLog(@"mutableStr:%p", mutableStr);
        NSLog(@"retainStr :%@", _stStr);
        NSLog(@"copyStr   :%@", _coStr);
    }

    控制器Log:

    2016-07-04 15:59:20.117 Demo_OC[20588:1058116] mutableStr:0x7fece3c13860, 0x7fff56bf8cd8
    2016-07-04 15:59:20.117 Demo_OC[20588:1058116] strongStr :0x7fece3c13860, 0x7fece3e8d428
    2016-07-04 15:59:20.118 Demo_OC[20588:1058116] copyStr   :0xa0000000063626130x7fece3e8d430
    
    
    2016-07-04 15:59:20.118 Demo_OC[20588:1058116] mutableStr:0x7fece3c13860
    2016-07-04 15:59:20.118 Demo_OC[20588:1058116] retainStr :abcde
    2016-07-04 15:59:20.118 Demo_OC[20588:1058116] copyStr   :abc

    通过日志我们可以分析:

    1、mutableStr 被修改时,strong修饰的字符串值发生了变化;copy修饰的字符串值未发生变化。

    结论:strong修饰的字符串仅仅是浅拷贝,本身会随着mutableStr改变而改变;而copy修改的字符串是深拷贝,不会随着mutableStr改变而改变。

    2、使用copy修饰的字符串更安全一些,可以保证我们的值不会随着mutableStr的改变而改变。

  • 相关阅读:
    js 获取服务端时间,并实现时钟
    微信分享问题记录
    format
    vue-cli3 使用mint-ui
    vue.js 使用记录(1)
    iview admin 生成环境打包时路径问题
    java8:(Lambda 表达式简介)
    SpringBoot: 18.使用Scheduled 定时任务器(转)
    SpringBoot: 16.整合junit单元测试(转)
    SpringBoot: 17.热部署配置(转)
  • 原文地址:https://www.cnblogs.com/xiu619544553/p/5644016.html
Copyright © 2011-2022 走看看