Objective-C中strong和copy区别

Objective-C中,strong和copy修饰符对NSString和NSMutableString有不同的影响。对于NSString,两者效果相同,仅保持引用。但对于NSMutableString,strong只会保留引用,而copy会创建一个新的不可变副本,确保对象内容不会被意外修改。
摘要由CSDN通过智能技术生成

Objective-C中strong和copy区别

在Objective-C开发中,我们经常使用strong和copy属性修饰符,对于NSString来说两者效果相同,而对于NSMutableString来说,两者含义不同。我们可以通过代码验证下。

NSString

@property (nonatomic, strong) NSString *strongString;
@property (nonatomic, copy) NSString *copiedString;


@property (nonatomic, strong) NSMutableString *strongMutableString;
@property (nonatomic, copy) NSMutableString *copiedMutableString;

在类的属性中,我们增加以上几个属性,strong和copy修饰的NSString,strong和copy修饰的NSMutableString。

 NSString *string = [NSString stringWithFormat:@"hello string, hello world!"];
 self.strongString = string;
 self.copiedString = string;
    
 NSLog(@"%p", string);
 NSLog(@"%p", self.strongString);
 NSLog(@"%p", self.copiedString);

生成一个NSString实例并且赋值,把string分别赋值给copiedString和strongString。运行程序后,可以发现三者的内存地址是相同的。这里%p即打印实例的地址。

iOSProject[71752:7608123] 0x600000164f00
iOSProject[71752:7608123] 0x600000164f00
iOSProject[71752:7608123] 0x600000164f00

三者内存地址相同,说明对于NSString来说strong和copy的作用是相同的。

NSMutableString

NSMutableString *mutableString = [[NSMutableString alloc] initWithFormat:@"hello mutableString, hello world!"];
self.strongMutableString = mutableString;
self.copiedMutableString = mutableString;
   
NSLog(@"%p", mutableString);
NSLog(@"%p", self.strongMutableString);
NSLog(@"%p", self.copiedMutableString);

写入NSMutableString代码,并且把mutableString分别赋值给strongMutableString和copiedMutableString,运行程序后三者内存地址不完全相同。mutableString和strongMutableString是相同的内存地址,而copiedMutableString是不同的内存地址,copiedMutableString在赋值过程过程中发生了拷贝。

iOSProject[71842:7610995] 0x600002e0f330
iOSProject[71842:7610995] 0x600002e0f330
iOSProject[71842:7610995] 0x60000350d580
  [mutableString replaceOccurrencesOfString:@", hello world!" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, mutableString.length)];
  NSLog(@"%@", mutableString);
  NSLog(@"%@", self.strongMutableString);
  NSLog(@"%@", self.copiedMutableString);

修改代码,把mutableString的字符串内容做替换,再打印三个实例对象的取值,可以发现

mutableString值发生改变,strongMutableString的值也发生了改变。copiedMutableString并没有发生改变,因为它指向的是另外一块内存地址。

iOSProject[71842:7610995] hello mutableString
iOSProject[71842:7610995] hello mutableString
iOSProject[71842:7610995] hello mutableString, hello world!

总结

对于NSString来说,strong和copy的作用相同,都是让属性指向同一块内存。

对于NSMutableString来说,strong指向的是同一块内存,而copy指向的是新生成的内存。

在实际的开发中,NSString也可以指向NSMutableString,如果不想修改原来的内存,这个时候可以使用copy修饰属性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值