iOS学习笔记3-NSString为什么用copy修饰而不用strong

目的:我们修改字符串的时候,是不想连带把属性也修改的

测试结果是:

用strong修饰的NSString会

#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) NSString *strongString;
@property (nonatomic, copy) NSString *copyedString;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self demo2];
    // 对于不可变字符串而言,使用strong和copy都是浅拷贝,打印的地址都是一致的
    NSString *string = [NSString stringWithFormat:@"123"];
    self.strongString = string;
    self.copyedString = string;
    NSLog(@" string: %p",string);
    NSLog(@" strongString : %p",self.strongString);
    NSLog(@" copyedString : %p",self.copyedString);

}
    
// 测试可变字符串使用copy属性(其实使用copy属性 相当于该变量进行了一次copy操作[string copy])
- (void)demo2{

    // 不可变字符串
    NSMutableString *string = [NSMutableString stringWithFormat:@"123"];
    // 用strong修饰的属性记录
    self.strongString = string;
    // 用copy修饰的属性记录
    self.copyedString = string;
    // 打印地址
    NSLog(@" string: %p",string);
    NSLog(@" strongString : %p",self.strongString);
    NSLog(@" copyedString : %p",self.copyedString);
    NSLog(@"%@",self.copyedString);
    // 改变字符串,对比用strong和copy修饰的属性的区别
    [string appendString:@"bbb"];
    NSLog(@" strongString : %@  %p",self.strongString, self.strongString);
    NSLog(@" copyedString : %@  %p",self.copyedString, self.copyedString);

}
@end

小结:

demo2 打印结果:

我们发现用copy修饰的属性地址已经变了,原因是NSMutableString的对象copy操作 产生新地址,产生的是不可变的对象,所以改变string,,不会改变被copy修饰的属性.正好符合我们改变string 不会改变self.copyedstring的值,而self.strongstring的值已经改变了

2016-01-29 18:51:16.227 strongAndCopy[1804:166346]  string: 0x7ae3a0c0

2016-01-29 18:51:16.227 strongAndCopy[1804:166346]  strongString : 0x7ae3a0c0

2016-01-29 18:51:16.228 strongAndCopy[1804:166346]  copyedString : 0x7ae39510

2016-01-29 18:51:16.228 strongAndCopy[1804:166346] 123

2016-01-29 18:51:16.228 strongAndCopy[1804:166346]  strongString : 123bbb  0x7ae3a0c0

2016-01-29 18:51:16.228 strongAndCopy[1804:166346]  copyedString : 123  0x7ae39510


转载于:https://my.oschina.net/u/2617794/blog/608633

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值