第一、淺拷貝:
Car *car=[[[self class] allocWithZone:zone] init]; car.engine=_engine; car.name=_name; car.weight=_weight; return car;
測試代碼:
Car *car = [[Car alloc] init]; Engine *engine = [[Engine alloc] init]; car.engine = engine; [engine release]; //NSLog(@"engine retaincount is %lu",[engine retainCount]); car.name = @"奧迪"; car.weight = @1000; Car *car2=[car copy]; // NSLog(@"car2 retaincount is %lu",[car2 retainCount]); NSLog(@"car %@,car2:%@",car.engine,car2.engine);
car
第二、深拷貝:
- (id)copyWithZone:(NSZone *)zone { /***淺拷貝**/ Car *car=[[[self class] allocWithZone:zone] init]; Engine *engineCopy=[[_engine copy] autorelease]; car.engine=engineCopy; NSString *namecopy=[[_name copy] autorelease]; car.name=namecopy; NSNumber *weightcopy=[[_weight copy] autorelease]; car.weight=weightcopy; return car; }
Car *car = [[Car alloc] init]; Engine *engine = [[Engine alloc] init]; car.engine = engine; [engine release]; //NSLog(@"engine retaincount is %lu",[engine retainCount]); car.name = @"奧迪"; car.weight = @1000; Car *car2=[car copy]; // NSLog(@"car2 retaincount is %lu",[car2 retainCount]); NSLog(@"car %@,car2:%@",car.engine,car2.engine);
car
Car *car=[[[self class] allocWithZone:zone] init];
另外,當子類繼承了父類時,他繼承了父類的一切屬性,包括要實現的協議
第三、NSFoundation,當我們copy的時一個不可變對象時,默認的copy都是淺拷貝,相當於retain
NSArray *array =[NSArray arrayWithObjects:@"one",@"two",@"three", nil]; NSArray *array1 = [array copy]; NSLog(@"%p",array); NSLog(@"%p",array1); NSLog(@"the retaincount is %lu",[array retainCount]);
copyDemo1[673:303] 0x10010a5d0
2013-12-28 20:01:10.969 copyDemo1[673:303] 0x10010a5d0
2013-12-28 20:01:10.969 copyDemo1[673:303] the retaincount is 2
注意retaincount會增加當使用mutableCopy時,不管對象是否可變,都會實現深拷貝
NSArray *array =[NSArray arrayWithObjects:@"one",@"two",@"three", nil]; NSMutableArray *array1 = [array mutableCopy]; NSLog(@"%p",array); NSLog(@"%p",array1); NSLog(@"the retaincount is %lu",[array retainCount]);
copyDemo1[695:303] 0x10010a5d0
2013-12-28 20:07:08.570 copyDemo1[695:303] 0x10010b260
2013-12-28 20:07:08.570 copyDemo1[695:303] the retaincount is 1
第四、retain相當於兩個對象指向同一個指針NSMutableArray *array1 = [[NSMutableArray alloc] initWithObjects:@"one",@"two",@"three",@"foure", nil]; NSMutableArray *array2 = [array1 retain]; [array2 removeLastObject]; NSLog(@"%@",array1); NSLog(@"the retaincount is %ld",array2.retainCount);結果:
2013-12-28 20:13:02.915 copyDemo1[736:303] ( one, two, three ) 2013-12-28 20:13:02.917 copyDemo1[736:303] the retaincount is 2