DJe*_*ean 0 objective-c automatic-ref-counting
现在它没有ARC中的复制属性,所以当我想复制一个对象时该怎么做?然后我写了一个测试代码:
test.h
@property (strong, nonatomic) NSMutableString *str1;
@property (strong, nonatomic) NSMutableString *str2;
Run Code Online (Sandbox Code Playgroud)
test.m
self.str1 = [[NSMutableString alloc] initWithString:@"Hello"];
self.str2 = [self.str1 copy];
[self.str2 appendString:@"World"];
NSLog(@"str1:%@,str2:%@",self.str1,self.str2);
Run Code Online (Sandbox Code Playgroud)
当我跑,它崩溃了:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendString:'
Run Code Online (Sandbox Code Playgroud)
那么,我该怎么办?
copy应始终返回对象的不可变副本,并且mutableCopy(如果可用)应始终返回可变对象,无论接收器是可变的还是不可变的.通过这种方式,您可以确定当您要求copy它时它将是不可变的,当您要求mutableCopy它时它将是可变的.
这个概念已存在多年,并不是特定于ARC.ARC只处理对象的内存管理,而不是它们的可变性.