IOS開發中的深拷貝、淺拷貝

        NSLog(@"Hello, World!");數組



//        NSString *str1 = @"STR";app

//        NSString *str2 = [str1 copy];測試

//spa

//        NSLog(@"%p -> %p",&str1, str1);指針

//        NSLog(@"%p -> %p",&str2, str2);對象

//        NSLog(@"引用計數: %lu", (unsigned long)[str1 retainCount]);rem


#pragma 字符串類型的深拷貝、淺拷貝字符串

        NSMutableString *string = [NSMutableString stringWithString: @"origion"];string

        NSString *stringCopy = [string copy];it

        NSMutableString *mStringCopy = [string copy];

        NSMutableString *stringMCopy = [string mutableCopy];

//        [mStringCopy appendString:@"mm"];//error

//        [string appendString:@" origion!"];

//        [stringMCopy appendString:@"!!"];

        NSLog(@"string:->%p", string);

        NSLog(@"string:->%p", stringCopy);

        NSLog(@"string:->%p", mStringCopy);

        NSLog(@"string:->%p\n\n", stringMCopy);


#pragma 容器類型的深拷貝、淺拷貝

        //不可變類型的深拷貝、淺拷貝和字符串相似

        //可變容器類型的copymutablecopy都是深拷貝,可是copy的對象不可變

        //拷貝的容器類型的裏面的元素都是淺拷貝,只是複製指針


        //copy返回不可變對象,mutablecopy返回可變對象

        NSArray *array1 = [NSArray arrayWithObjects:@"a",@"b",@"c",nil];

        NSArray *arrayCopy1 = [array1 copy];

        //arrayCopy1是和array同一個NSArray對象(指向相同的對象),包括array裏面的元素也是指向相同的指針

        NSLog(@"array1 retain count: %d",[array1 retainCount]);

        NSLog(@"array1 retain count: %d\n\n",[arrayCopy1 retainCount]);

        NSMutableArray *mArrayCopy1 = [array1 mutableCopy];

        //mArrayCopy1array1的可變副本,指向的對象和array1不一樣,可是其中的元素和array1中的元素指向的是同一個對象。mArrayCopy1還能夠修改本身的對象

        [mArrayCopy1 addObject:@"de"];

        [mArrayCopy1 removeObjectAtIndex:0];


        NSArray *mArray1 = [NSArray arrayWithObjects:[NSMutableString stringWithString:@"a"],@"b",@"c",nil];

        NSArray *mArrayCopy2 = [mArray1 copy];

        NSLog(@"mArray1 retain count: %d",[mArray1 retainCount]);

        NSMutableArray *mArrayMCopy1 = [mArray1 mutableCopy];

        NSLog(@"mArray1 retain count: %d",[mArray1 retainCount]);

        //mArrayCopy2,mArrayMCopy1mArray1指向的都是不同的對象,可是其中的元素都是同樣的對象——同一個指針

        //一下作測試

        NSMutableString *testString = [mArray1 objectAtIndex:0];

        //testString = @"1a1";//這樣會改變testString的指針,實際上是將@「1a1」臨時對象賦給了testString

        [testString appendString:@" tail"];//這樣以上三個數組的首元素都被改變了



        NSMutableArray *Marray = [NSMutableArray arrayWithObjects:[NSMutableString stringWithString:@"a"],@"b",@"c",nil];

        NSMutableArray *copyArray = [Marray copy];

        NSMutableArray *McopyArray = [Marray mutableCopy];

        NSMutableString *str = [McopyArray objectAtIndex:0];

        [str appendString:@"bc"];

        NSLog(@"array1 retain count: %d",[Marray retainCount]);

        NSLog(@"array1 retain count: %d\n\n",[copyArray retainCount]);

        NSLog(@"%@",McopyArray);

相關文章
相關標籤/搜索