IOS开发中的深拷贝、浅拷贝

        NSLog(@"Hello, World!");



//        NSString *str1 = @"STR";

//        NSString *str2 = [str1 copy];

//

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

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

//        NSLog(@"引用计数: %lu", (unsigned long)[str1 retainCount]);


#pragma 字符串类型的深拷贝、浅拷贝

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

        NSString *stringCopy = [string copy];

        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);


你可能感兴趣的:(IOS开发中的深拷贝、浅拷贝)