標籤:
-(void)copyDemo{// 在非集合類對象中:對immutable對象進行copy操作,是指標複製,mutableCopy操作時內容複寫;對mutable對象進行copy和mutableCopy都是內容複寫。用代碼簡單表示如下:// // [immutableObject copy] // 淺複製// [immutableObject mutableCopy] //深複製// [mutableObject copy] //深複製// [mutableObject mutableCopy] //深複製 // 在集合類對象中,對immutable對象進行copy,是指標複製,mutableCopy是內容複寫;對mutable對象進行copy和mutableCopy都是內容複寫。但是:集合對象的內容複寫僅限於對象本身,對象元素仍然是指標複製。用代碼簡單表示如下:// // [immutableObject copy] // 淺複製// [immutableObject mutableCopy] //單層深複製// [mutableObject copy] //單層深複製// [mutableObject mutableCopy] //單層深複製 // Baby *baby = [[Baby alloc] init]; //必須實現copy方法// baby.babyName = @"wei"; NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:10]; [dic setObject:@"1" forKey:@"key1"]; NSMutableArray *array1 = [[NSMutableArray alloc] initWithObjects:dic,dic, nil]; NSMutableArray *array2 = [array1 mutableCopy];//單層深拷貝 NSMutableArray *array3 = [[NSMutableArray alloc] initWithArray:array1 copyItems:YES];//裡面dic變成不可變了 NSMutableArray* array4 = [NSKeyedUnarchiver unarchiveObjectWithData: [NSKeyedArchiver archivedDataWithRootObject: array1]];//裡面dic改變不影響其他數組(其與方法都會影響其他數組) [array2 removeObjectAtIndex:0]; [[array4 objectAtIndex:0] setObject:@"3" forKey:@"key1"];// [[array4 objectAtIndex:1] setBabyName:@"8888"]; DLog(@"%@ \n %@ \n %@ \n %@",array1,array2,array3,array4);}
iOS 深淺拷貝