小轩卡盟,儿女传奇之分身,邪魔导
ios深拷贝和浅拷贝解析。最近项目中遇到一些有关自定义对象的copy问题,今天在这里做一些记录。以便加深理解和记忆。
1.1 nsstring
nsstring *string1 = @"str1"; //copy返回的是不可变对象,str2不能被修改,因此会发生崩溃 nsstring *string2 = [string1 copy]; nslog(@"string1: %p %p,string2: %p %p",string1,&string1,string2,&string2); nsmutablestring *string3 = [string1 mutablecopy]; nslog(@"string1: %p %p,string3: %p %p",string1,&string1,string3,&string3); 2017-08-03 20:26:26.450 tableviewtest[77698:6624676] string1: 0x10092e0f8 0x7fff5f2d5980,string2: 0x10092e0f8 0x7fff5f2d5978 2017-08-03 20:26:26.450 tableviewtest[77698:6624676] string1: 0x10092e0f8 0x7fff5f2d5980,string3: 0x608000077b00 0x7fff5f2d5970
从打印的内容可以看的出来string1、string2内容的地址相同,而string1、string2指针的地址不同。string1、string3内容的地址和指针地址都不相同。可知nsstring的copy为浅拷贝,mutablecopy为深拷贝
1.2 nsmutablestring
nsmutablestring *mstr1 = [nsmutablestring stringwithstring:@"test002"]; nsmutablestring *mstr2 = [mstr1 copy]; nslog(@"mstr1: %p %p,mstr2: %p %p",mstr1,&mstr1,mstr2,&mstr2); //copy返回的是不可变对象,mstr2不能被修改,因此会发生崩溃 //[mstr2 appendstring:@"test"]; nsmutablestring *mstr3 = [mstr1 mutablecopy]; //[mstr3 appendstring:@"modify"]; nslog(@"mstr1: %p %p,mstr3: %p %p",mstr1,&mstr1,mstr3,&mstr3); 2017-08-03 20:49:28.896 tableviewtest[78081:6667312] mstr1: 0x6000000767c0 0x7fff51c74980,mstr2: 0xa323030747365747 0x7fff51c74978 2017-08-03 20:49:28.896 tableviewtest[78081:6667312] mstr1: 0x6000000767c0 0x7fff51c74980,mstr3: 0x600000076800 0x7fff51c74970
从打印的内容可以看的出来mstr1、mstr2、mstr3内容地址和指针地址都不相同。所以nsmutablestring的copy和mutablecopy都是深拷贝。且copy返回的对象是不可变对象
2.1 不可变对象nsarray
nsarray *arry1 = [[nsarray alloc] initwithobjects:@"value1", @"value2",nil]; nsarray *arry2 = [arry1 copy]; nsarray *arry3 = [arry1 mutablecopy]; nslog(@"arry1: %p %p,arry2: %p %p",arry1,&arry1,arry2,&arry2); nslog(@"arry1: %p %p,arry3: %p %p",arry1,&arry1,arry3,&arry3); 2017-08-03 20:58:29.940 tableviewtest[78209:6684329] arry1: 0x608000223a00 0x7fff5f16f980,arry2: 0x608000223a00 0x7fff5f16f978 2017-08-03 20:58:29.940 tableviewtest[78209:6684329] arry1: 0x608000223a00 0x7fff5f16f980,arry3: 0x608000245280 0x7fff5f16f970
从打印的内容可以看的出来arry1、arry2内容的地址相同,而arry1、arry2指针的地址不同。arry1、arry3内容的地址和指针地址都不相同。可知nsstring的copy为浅拷贝,mutablecopy为深拷贝
2.2 可变对象nsmutablearray
nsmutablearray *arry1 = [[nsmutablearray alloc] initwithobjects:@"value1", @"value2",nil]; nsmutablearray *arry2 = [arry1 copy]; //copy返回的是不可变对象,marry2不能被修改,因此会崩溃 //[arry2 addobject:@"value3"]; nsmutablearray *arry3 = [arry1 mutablecopy]; nslog(@"arry1: %p %p,arry2: %p %p",arry1,&arry1,arry2,&arry2); nslog(@"arry1: %p %p,arry3: %p %p",arry1,&arry1,arry3,&arry3);
从打印的内容可以看的出来arry1、arry2、arry3内容地址和指针地址都不相同。所以nsmutablestring的copy和mutablecopy都是深拷贝。且copy返回的对象是不可变对象
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
网友评论