淺復制示例代碼:
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的方法,可以使用這些方法創建對象的副本,通過實現一個符合
然而Foundation類的copy和mutableCopy方法,默認情況下只是對對象創建的一個新的引用,他們都指向同一塊內存,也就是淺復制。因此就會出現上面的結果。
@protocol NSCopying - (id)copyWithZone:(NSZone *)zone; @end @protocol NSMutableCopying - (id)mutableCopyWithZone:(NSZone *)zone; @end
@interface DemoObject : NSObject@property (strong, nonatomic) NSString *name; @end @implementation DemoObject - (id)copyWithZone:(NSZone *)zone { DemoObject* object = [[[self class] allocWithZone:zone]init]; return object; } @end
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.150 AppTest[14507:122304] object.name = object
2015-04-23 15:18:15.151 AppTest[14507:122304] newObject.name = newObject
說明:
自定義類中,必須實現
參數zone與不同的存儲區有關,你可以在程序中分配並使用這些存儲區,只有在編寫要分配大量內存的應用程序並且想要通過將空間分配分組到這些存儲區中來優化內存分配時,才需要處理這些zone。可以使用傳遞給copyWithZone:的值,並將它傳給名為allocWithZone:的內存分配方法。這個方法在指定存儲區中分配內存。