第一、淺拷貝:
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 ,car2:
可以看出淺複製只是複製指標,並沒有建立新的記憶體空間
第二、深拷貝:
- (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 ,car2:
開闢了新的空間,zone代表一塊記憶體空間
Car *car=[[[self class] allocWithZone:zone] init];
注意上述代碼用的是【self class】,而不是car,因為如果是用car,那麼car的子類在調用此方法去實現copy協議時,就會出現記憶體問題
另外,當子類繼承了父類時,他繼承了父類的一切屬性,包括要實現的協議
第三、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