iOS開發中,對象擁有複製特性,必須實現NSCopying,NSMutableCopying協議,實現該協議的copyWithZone方法和mutableCopyWithZone方法
深拷貝和淺拷貝的區別就在於copyWithZone方法的實現,
淺拷貝代碼如下:
?
1 2 3 4 5 6 7 8 |
#import <foundation foundation.h="">
@interface Person : NSObject<nscopying> @property(nonatomic,retain)NSString *name; @property(nonatomic,retain)NSString *age;
@end </nscopying></foundation> |
?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#import "Person.h"
@implementation Person
- (id)copyWithZone:(NSZone *)zone { //實現自定義淺拷貝 Person *person=[[self class] allocWithZone:zone]; person.age=_age; person.name=_name; return person; } @end |
main函數爲:
?
1 2 3 4 5 6 7 8 9 |
@autoreleasepool {
Person *person=[[Person alloc] init]; person.name=@"andy"; person.age=@"20";
Person *person2=[person copy]; NSLog(@"person 地址爲%p,person2地址爲%p",person.name,person2.name); } |
輸出結果爲:
?
1 |
2013-09-30 17:48:41.007 FDAS[732:303] person 地址爲0x1000022c8,person2地址爲0x1000022c8 |
深拷貝代碼如下:
?
1 2 3 4 5 6 7 8 |
- (id)copyWithZone:(NSZone *)zone { //實現自定義淺拷貝 Person *person=[[self class] allocWithZone:zone]; person.age=[_age copy]; person.name=[_age copy]; return person; } |
結果:
?
1 |
2013-09-30 17:55:13.603 FDAS[742:303] person 地址爲0x1000022c8,person2地址爲0x1000022e8 |
?
1 2 3 4 |
NSArray *arr=[NSArray arrayWithObjects:@"one",@"two",nil]; NSArray *arr2=[arr copy]; NSLog(@"the dress of arr is %p the dress of arr2 is %p",arr,arr2); NSLog(@"the retainCount is %ld",arr.retainCount); |
執行結果爲:
2015-09-30 18:01:01.394 FDAS[787:303] the dress of arr is 0x100108320 the dress of arr2 is 0x100108320
2015-09-30 18:01:01.396 FDAS[787:303] the retainCount is 2
結果是一樣的,是因爲Foundation對於不可變複製對象而言,copy方法做了優化,相當於retain,故retaincount變成2.
相當於 在copyWithZone方法中:return [self retain];
歡迎大家批評指正~