// // ViewController.m // 18章複製對象 // // Created by Zoujie on 15/11/21. // Copyright © 2015年 Zoujie. All rights reserved. // #import "ViewController.h" #import "Book.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. #pragma mark copy and mutableCopy method [self copyAndMutableCopy]; #pragma mark 淺複製與深複製 [self copyAnddeepCopy]; [self DictionaryDemo]; } -(void)copyAndMutableCopy { // NSArray *array = @[@"one",@"two",@"three",@"four"]; NSMutableArray *array = [NSMutableArray arrayWithObjects:@"one",@"two",@"three",@"four", nil]; NSMutableArray *dataArray; NSMutableArray *dataArray2; //通常賦值 // dataArray = [NSMutableArray arrayWithArray:array]; dataArray = array; [dataArray removeObjectAtIndex:0]; NSLog(@"dataArray===%@,array===%@,%p,%p",dataArray,array,dataArray,array); NSLog(@"%p,%p",[dataArray objectAtIndex:0],[array objectAtIndex:0]);// 打印內存地址 //複製一份,而後刪除副本第一個元素 dataArray2 = [array mutableCopy]; [dataArray2 removeObjectAtIndex:0]; NSLog(@"dataArray===%@,array===%@",dataArray2,array); } -(void)copyAnddeepCopy { NSMutableArray *dataArray = [NSMutableArray arrayWithObjects:[NSMutableString stringWithString:@"one"],[NSMutableString stringWithString:@"two"],[NSMutableString stringWithString:@"three"], nil]; NSMutableArray *dataArray2; NSMutableString *mStr; NSLog(@"dataArray: "); for (NSString *elem in dataArray) NSLog(@" %@",elem); // 複製一份,而後刪除副本的一個元素 dataArray2 = [dataArray mutableCopy]; mStr = dataArray[0]; [mStr appendString:@"ONE"]; //原始數組第一個元素也沒修改了 //淺複製僅將數組元素的引用複製到了另外一個數組元素 NSLog(@"dataArray: "); for (NSString *elem in dataArray) NSLog(@" %@",elem); NSLog(@"dataArray2: "); for (NSString *elem in dataArray2) NSLog(@" %@",elem); //若要爲數組中的每一個元素建立徹底不一樣的副本,須要執行深複製 // Book *book = [[Book alloc]init]; // Book *newbook; // newbook = [book mutableCopy]; // 想要實現本身建立的類的複製,須要實現nscoping協議的方法 } -(id)copyWithZone:(NSZone *)zone { // Fraction *newFraction = [[Fraction allocWithZone:zone]init]; // //// [newFraction set] return nil; } -(void)DictionaryDemo { NSDictionary *dicDemo = [[NSDictionary alloc]init]; dicDemo = @{@"firstName":@"zou",@"Seconde":@"Jie",@"age":@"28"}; NSMutableDictionary *dicCopy; dicCopy = [dicDemo copy]; NSLog(@"dicCopy=======================================================%@",dicCopy); NSLog(@"dicDemo=======================================================%@",dicDemo); // [dicCopy removeObjectForKey:@"firstName"]; // // } @end