浅复制示例代码:
NSMutableArray *mArray = [NSMutableArray arrayWithObjects: [NSMutableString stringWithString: @"origionA"], [NSMutableString stringWithString: @"origionB"], [NSMutableString stringWithString: @"origionC"], nil]; NSMutableArray *mArrayCopy = [mArray mutableCopy]; NSMutableString *string = [mArray objectAtIndex:0]; [string appendString:@"Append"]; [mArrayCopy removeObjectAtIndex:1]; NSLog(@"object.name = %@",mArray); NSLog(@"object.name = %@",mArrayCopy);
2015-04-23 15:18:15.151 AppTest[14507:122304] object.name = (
origionAAppend,
origionB,
origionC
)
2015-04-23 15:18:15.151 AppTest[14507:122304] object.name = (
origionAAppend,
origionC
)
说明:
Foundation类实现了名为copy和mutableCopy的方法,可以使用这些方法创建对象的副本,通过实现一个符合<NSCopying>协议(如下代码)的方法来完成这个工作,如果必须区分要产生的对象是可变副本还是不可变副本,那么通过<NSCopying>协议来产生不可变副本,通过<NSMutableCopying>协议来产生可变副本。
然而Foundation类的copy和mutableCopy方法,默认情况下只是对对象创建的一个新的引用,他们都指向同一块内存,也就是浅复制。因此就会出现上面的结果。
@protocol NSCopying - (id)copyWithZone:(NSZone *)zone; @end @protocol NSMutableCopying - (id)mutableCopyWithZone:(NSZone *)zone; @end
@interface DemoObject : NSObject<NSCopying> @property (strong, nonatomic) NSMutableString *name; @end @implementation DemoObject - (id)copyWithZone:(NSZone *)zone { DemoObject* object = [[[self class] allocWithZone:zone]init]; return object; } - (id)init { self = [super init]; if (self) { self.name = [NSMutableString stringWithString: @"name"]; } return self; } @end
DemoObject* demoObject = [[DemoObject alloc]init]; [demoObject.name appendString:@"Append"]; DemoObject* newDemoObject = [demoObject copy]; [newDemoObject.name appendString:@"NewAppend"]; NSLog(@"demoObject.name = %@",demoObject.name); NSLog(@"newDemoObject.name = %@",newDemoObject.name);
demoObject.name = nameAppend
newDemoObject.name = nameNewAppend
说明:
自定义类中,必须实现<NSCopying>或者<NSMutableCopying>协议并实现copyWithZone:或者mutableCopyWithZone:方法,才能响应copy和mutableCopy方法来复制对象。
参数zone与不同的存储区有关,你可以在程序中分配并使用这些存储区,只有在编写要分配大量内存的应用程序并且想要通过将空间分配分组到这些存储区中来优化内存分配时,才需要处理这些zone。可以使用传递给copyWithZone:的值,并将它传给名为allocWithZone:的内存分配方法。这个方法在指定存储区中分配内存。