浅拷贝:
浅拷贝就是对内存地址的复制,让目标对象指针和源对象指向同一片内存空间。
深拷贝:
深拷贝是指拷贝的具体对象的内容,而内存地址是自助分配的,拷贝结束之后,两个对象虽然存在的值是相同的,但是内存地址不一样,两个对象也互不影响,互不干涉。
非容器不可变对象:
//非容器不可变对象
NSString *str = @"teststr"; //1
NSString *strCopy = [str copy]; //2
NSMutableString *strMCoppy = [str mutableCopy];//1
[strMCoppy appendString:@"oo"];//no error
NSLog(@"str-p = %p",str); //0x100001030
NSLog(@"strCopy-p = %p",strCopy); //0x100001030
NSLog(@"strMCopy-p = %p",strMCoppy); //0x100506a20
copy复制的是指针,mutableCopy生成新的内存地址,并且返回的对象为可变对象
非容器可变对象:
//非容器可变对象
NSMutableString *mStr = [NSMutableString stringWithFormat:@"testStr"];
NSString *strCopy = [mStr copy];
NSMutableString *mStrCopy = [mStr copy];
NSMutableString *mStrMCopy = [mStr mutableCopy];
[mStrCopy appendString:@"0"];//error
[mStrMCopy appendString:@"0"];//no error
NSLog(@"mStr-p = %p",mStr); //0x1001065d0
NSLog(@"strCopy-p = %p",strCopy); //0x7274537473657475
NSLog(@"mStrCopy-p = %p",mStrCopy); //0x7274537473657475
NSLog(@"mStrMCopy-p = %p",mStrMCopy); //0x1001067f0
1.copy对可变对象非容器类为深拷贝。(对象地址为何是同一个???)
2.mutableCopy对可变非容器类为深拷贝。
3.copy产生的对象返回的为不可变。
容器类非可变对象
//容器类不可变对象
NSArray *array1 = [NSArray arrayWithObjects:@"a",@"b",@"c", nil];
NSArray *arrCopy1 = [array1 copy]; //指针复制
NSMutableArray *mArrCopy1 = [array1 mutableCopy]; //对象复制(里面的元素为指针复制)
NSLog(@"array-p = %p",array1); //0x1002043c0
NSLog(@"arrCopy-p = %p",arrCopy1); //0x1002043c0
NSLog(@"mArrCopy-p = %p",mArrCopy1); //0x100203900
NSArray *array2 = [NSArray arrayWithObjects:[NSMutableString stringWithString:@"a"],@"b",@"c", nil];
NSArray *arrCopy2 = [array2 copy]; //指针复制
NSMutableArray *mArrCopy2 = [array2 mutableCopy]; //对象复制(里面的元素为指针复制)
NSLog(@"array-p = %p",array2); //0x100105c50
NSLog(@"arrCopy-p = %p",arrCopy2); //0x100105c50
NSLog(@"mArrCopy-p = %p",mArrCopy2); //0x100106f60
//由此可见,对于容器而言,其元素对象始终是指针复制。如果需要元素对象也是对象复制,就需要实现深拷贝。
//http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Articles/Copying.html
NSArray *deepCopyArray=[[NSArray alloc] initWithArray: array2 copyItems: YES];
NSArray* trueDeepCopyArray = [NSKeyedUnarchiver unarchiveObjectWithData:
[NSKeyedArchiver archivedDataWithRootObject: array2]];
NSLog(@"deepCopyArray-p = %p",deepCopyArray); //第一个元素对象复制,其他指针复制
NSLog(@"trueDeepCopyArray-p = %p",trueDeepCopyArray); //容器内元素全部对象复制
结论:
1.copy:对于可变对象为深复制;对于不可变对象是浅复制,引用计数每次加一,始终返回不可变的对象。(?)
2.mutableCopy:始终是深复制,始终返回一个可变对象。
3.对于容器而言,其元素对象始终是指针复制。如果需要元素对象也是对象复制,就需要实现深拷贝。http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Articles/Copying.html
网友评论