简体   繁体   English

如何在ARC中复制对象

[英]How to copy an object in ARC

Now it hasn't the copy property in ARC,so how should I do when I want copy an object? 现在它在ARC中没有copy属性,那么当我要复制对象时该怎么办? Then I write a test code: 然后我写一个测试代码:

test.h 测试

@property (strong, nonatomic) NSMutableString *str1;
@property (strong, nonatomic) NSMutableString *str2;

test.m 测试

self.str1 = [[NSMutableString alloc] initWithString:@"Hello"];
self.str2 = [self.str1 copy];
[self.str2 appendString:@"World"];
NSLog(@"str1:%@,str2:%@",self.str1,self.str2);

When I run,it got crash: 当我跑步时,它崩溃了:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendString:'

So,how should I do? 那么,我该怎么办?

copy should always returns immutable copies of objects, and mutableCopy (if available) should always returns mutable objects, regardless of whether the receiver is mutable or immutable. copy应该始终返回对象的不可变副本,而mutableCopy (如果有)应始终返回可变对象,而不管接收者是可变对象还是不可变对象。 This way, you can be sure that when you ask for a copy it will be immutable and when you ask for a mutableCopy it will be mutable. 通过这种方式,你可以肯定,当你问一个copy是不变的,当你问一个mutableCopy是可变的。

This concept has been around for years, and is not specific to ARC. 这个概念已经存在了很多年,并且并不专门针对ARC。 ARC simply handles the memory management of objects, not their mutability. ARC仅处理对象的内存管理,而不处理对象的可变性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM