0

现在ARC里没有copy属性了,我想复制一个对象怎么办?然后我写了一个测试代码:

测试.h

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

测试.m

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

当我运行时,它崩溃了:

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

那么,我该怎么办?

4

1 回答 1

6

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.

于 2012-05-17T03:53:11.870 回答