简体   繁体   中英

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? 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. 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.

This concept has been around for years, and is not specific to ARC. ARC simply handles the memory management of objects, not their mutability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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