复制对象 copy 与mutable copy

转载 :  http://blog.csdn.net/u010962810/article/details/18887841

通过copy方法可以创建可变对象或不可变对象的不可变副本,对于不可变副本,其对象的值不可以改变。

通过mutableCopy方法可以创建可变对象或不可变对象的可变副本,对于可变副本其对象是可变的。

复制分为浅复制和深复制两种:浅复制只是复制对象的引用,并没有复制对象的具体内容。深复制则创建了要复制对象的具体内容,并返回对象副本的引用。

对于复制Foundation中的对象,默认并不是深复制,例如copy NSMutableArray对象是浅复制,只是对其引用进行复制;而copy NSMutableString对象是深复制,对原来引用的对象的具体内容也进行了复制。

1.NSMutableArray和NSArray

首先创建1个数组(该数组中有3个对象)和4个数组指针:

NSMutableArray *marray1 = [NSMutableArray arrayWithObjects:
                                   [NSMutableString stringWithString:@"1"],
                                   [NSMutableString stringWithString:@"2"],
                                   [NSMutableString stringWithFormat:@"3"],
                                   nil];
        NSMutableArray *marray2 = [marray1 mutableCopy];
        NSArray *array1 = [marray1 copy];
        NSArray *array2 = [marray1 mutableCopy];

(1)添加字符串到marray1[0]中:

// append string to marray1[0]
        NSMutableString *mstr = marray1[0];
        [mstr appendString:@" append"];
        NSLog(@"append string to marray1[0]");
        NSLog(@"marray1 = %@", marray1);
        NSLog(@"marray2 = %@", marray2);
        NSLog(@"array1 = %@", array1);
        NSLog(@"array2 = %@", array2);
2014-01-31 21:10:39.097 Array[298:303] append string to marray1[0]
2014-01-31 21:10:39.098 Array[298:303] marray1 = (
    "1 append",
    2,
    3
)
2014-01-31 21:10:39.098 Array[298:303] marray2 = (
    "1 append",
    2,
    3
)
2014-01-31 21:10:39.098 Array[298:303] array1 = (
    "1 append",
    2,
    3
)
2014-01-31 21:10:39.099 Array[298:303] array2 = (
    "1 append",
    2,
    3
)

分析:

假设marray1中保存的是obj1,obj2,obj3组成的数组的首地址。将marray1复制给marray2,array1和array2,只是将指向数组第一个对象的内存地址复制到marray2等数组指针中保存。

在marray1[0]指向的对象obj1后面附加字符串append,由于marray1,marray2,array1和array2第一个指针指向的对象都是obj1,所以输出一致。

这里的copy方法和简单的赋值作用是一致的。

(2)为marray1[0]设置新的对象值:(注意(2)、(3)和(1)是相互独立的,下同)

// set new object to marray1[0]
        marray1[0] = [NSMutableString stringWithString:@"new 1"];
        NSLog(@"set new object to marray1[0]");
        NSLog(@"marray1 = %@", marray1);
        NSLog(@"marray2 = %@", marray2);
        NSLog(@"array1 = %@", array1);
        NSLog(@"array2 = %@", array2);
2014-01-31 20:50:52.003 Array[4151:303] set new object to marray1[0]
2014-01-31 20:50:52.004 Array[4151:303] marray1 = (
    "new 1",
    2,
    3
)
2014-01-31 20:50:52.005 Array[4151:303] marray2 = (
    1,
    2,
    3
)
2014-01-31 20:50:52.005 Array[4151:303] array1 = (
    1,
    2,
    3
)
2014-01-31 20:50:52.005 Array[4151:303] array2 = (
    1,
    2,
    3
)

分析:

这里创建了一个新的NSMutableString对象将其引用赋给marray1[0],而其他数组指针指向的对象不变,所以输出时其他数组不受影响。

(3)添加新的对象到marray1中:

// add new object to marray1
        [marray1 addObject:[NSMutableString stringWithString:@"4"]];
        NSLog(@"add new object to marray1");
        NSLog(@"marray1 = %@", marray1);
        NSLog(@"marray2 = %@", marray2);
        NSLog(@"array1 = %@", array1);
        NSLog(@"array2 = %@", array2);
2014-01-31 20:51:46.867 Array[4167:303] add new object to marray1
2014-01-31 20:51:46.869 Array[4167:303] marray1 = (
    1,
    2,
    3,
    4
)
2014-01-31 20:51:46.869 Array[4167:303] marray2 = (
    1,
    2,
    3
)
2014-01-31 20:51:46.869 Array[4167:303] array1 = (
    1,
    2,
    3
)
2014-01-31 20:51:46.869 Array[4167:303] array2 = (
    1,
    2,
    3
)

分析:

这里创建了一个新的可变字符串对象,并将其内存地址保存到指针marray1[3]中。而其他几个数组指针的引用不受影响。

(4)操作数组的引用

如果要单独替换marray1[0]指向的对象,应该先创建一个对象,然后再替换marray1[0]的引用。这样就不会对marray2[0]指向的对象造成影响。

NSMutableArray *marray1 = [NSMutableArray arrayWithObjects:
                                   [NSMutableString stringWithString:@"1"],
                                   [NSMutableString stringWithString:@"2"],
                                   [NSMutableString stringWithFormat:@"3"],
                                   nil];
        NSMutableArray *marray2 = [marray1 mutableCopy];
        NSArray *array1 = [marray1 copy];
        NSArray *array2 = [marray1 mutableCopy];
        NSMutableString *mstr = [NSMutableString stringWithString:marray1[0]]; // 创建新的对象
        [mstr appendString:@" append"];
        [marray1 replaceObjectAtIndex:0 withObject:mstr]; // 替换marray1[0]的引用

        NSLog(@"marray1 = %@", marray1);
        NSLog(@"marray2 = %@", marray2);
        NSLog(@"array1 = %@", array1);
        NSLog(@"array2 = %@", array2);

控制台输出:

2014-01-31 20:09:33.678 Dictionary[3735:303] marray1 = (
    "1 append",
    2,
    3
)
2014-01-31 20:09:33.679 Dictionary[3735:303] marray2 = (
    1,
    2,
    3
)
2014-01-31 20:09:33.680 Dictionary[3735:303] array1 = (
    1,
    2,
    3
)
2014-01-31 20:09:33.680 Dictionary[3735:303] array2 = (
    1,
    2,
    3
)

再看一个例子:

NSMutableArray *marray1 = [NSMutableArray arrayWithObjects:
                                   [NSMutableString stringWithString:@"1"],
                                   [NSMutableString stringWithString:@"2"],
                                   [NSMutableString stringWithFormat:@"3"],
                                   nil];
        NSMutableArray *marray2 = [marray1 mutableCopy];
        NSArray *array1 = [marray1 copy];
        NSArray *array2 = [marray1 mutableCopy];

        [marray1 removeObjectAtIndex:0];

        NSLog(@"marray1 = %@", marray1);
        NSLog(@"marray2 = %@", marray2);
        NSLog(@"array1 = %@", array1);
        NSLog(@"array2 = %@", array2);

控制台输出:

2014-01-31 20:10:40.716 Dictionary[3746:303] marray1 = (
    2,
    3
)
2014-01-31 20:10:40.717 Dictionary[3746:303] marray2 = (
    1,
    2,
    3
)
2014-01-31 20:10:40.717 Dictionary[3746:303] array1 = (
    1,
    2,
    3
)
2014-01-31 20:10:40.718 Dictionary[3746:303] array2 = (
    1,
    2,
    3
)

尽管marray1,marray2,array1,array2指向同一个数组对象,但是[marray1 removeObjectAtIndex:0]移除的是marray1第一个元素,即移除的是对对象的引用,而不是移除数组中的第一个对象。所以不会影响到marray2  ,array1,array2 。

2.NSMutableString和NSString

复制NSMutableString对象测试代码如下:

NSMutableString *mstr1 = [NSMutableString stringWithString:@"1"];
        NSMutableString *mstr2 = [mstr1 mutableCopy];
        NSString *str1 = [mstr1 copy];
        NSString *str2 = [mstr1 mutableCopy];

        [mstr1 appendString:@" append"];
        NSLog(@"mstr1 = %@", mstr1);
        NSLog(@"mstr2 = %@", mstr2);
        NSLog(@"str1 = %@", str1);
        NSLog(@"str2 = %@", str2);
2014-01-31 20:54:20.423 String[4221:303] mstr1 = 1 append
2014-01-31 20:54:20.424 String[4221:303] mstr2 = 1
2014-01-31 20:54:20.424 String[4221:303] str1 = 1
2014-01-31 20:54:20.424 String[4221:303] str2 = 1

分析:

对mstr1指向的对象STRING1进行复制,这里复制的是对象  STRING1 本身的内容,也就是mstr2,str1,str2将分别指向对象  STRING2,STRING3,STRING4,对STRING1的修改(在后面附加字符串),将不会影响到其他几个引用指向的对象。

可见这里进行的是深复制。

注意不要改变copy后的对象的值,因为copy生成的对象是不可变的,强行修改会导致程序崩溃。

控制台输出为:

2014-02-01 00:57:24.903 Array[792:303] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException‘, reason: ‘Attempt to mutate immutable object with appendString:‘

3.NSMutableDictionary和NSDictionary

首先创建1个字典(字典中对应3个对象)和4个字典指针:

NSMutableString *obj1 = [NSMutableString stringWithString:@"obj1"];
        NSMutableString *obj2 = [NSMutableString stringWithString:@"obj2"];
        NSMutableString *obj3 = [NSMutableString stringWithString:@"obj3"];
        NSMutableDictionary *mdic1 = [NSMutableDictionary dictionaryWithObjects:@[obj1, obj2, obj3]
                                                                        forKeys:@[@"key1", @"key2", @"key3"]];
        NSMutableDictionary *mdic2 = [mdic1 mutableCopy];
        NSDictionary *dic1 = [mdic1 copy];
        NSDictionary *dic2 = [mdic1 copy];

假设指针mdic1的索引key1,key2,key3分别对应对象obj1,obj2,obj3的内存地址。

对字典进行复制也是浅复制。

对mdic1复制,并赋值给mdic2,dic1,dic2,那么mdic2,dic1,dic2中指向的是同一个字典。

(1)添加字符串到mdic1的key1对应的可变字符串对象后:

// append string to mdic1[@"key1"]
        NSMutableString *mstr = mdic1[@"key1"];
        [mstr appendString:@" append"];
        NSLog(@"append string to midc1[@\"key1\"]");
        NSLog(@"mdic1 = %@", mdic1);
        NSLog(@"mdic2 = %@", mdic2);
        NSLog(@"dic1 = %@", dic1);
        NSLog(@"dic2 = %@", dic2);
2014-01-31 22:07:29.241 Dictionary[431:303] append string to midc1[@"key1"]
2014-01-31 22:07:29.242 Dictionary[431:303] mdic1 = {
    key1 = "obj1 append";
    key2 = obj2;
    key3 = obj3;
}
2014-01-31 22:07:29.243 Dictionary[431:303] mdic2 = {
    key1 = "obj1 append";
    key2 = obj2;
    key3 = obj3;
}
2014-01-31 22:07:29.243 Dictionary[431:303] dic1 = {
    key1 = "obj1 append";
    key2 = obj2;
    key3 = obj3;
}
2014-01-31 22:07:29.243 Dictionary[431:303] dic2 = {
    key1 = "obj1 append";
    key2 = obj2;
    key3 = obj3;
}

上面代码中对key1对应的对象obj1进行修改(在对象后面附加字符串),由于mdic2等指向同一个字典,所以其输出将会和mdic1的输出一致。

(2)设置新的对象给key1:

// set new object for  key1
        NSMutableString *nobj1 = [NSMutableString stringWithString:@"new obj1"];
        [mdic1 setObject:nobj1 forKey:@"key1"];
        NSLog(@"set new object for key");
        NSLog(@"mdic1 = %@", mdic1);
        NSLog(@"mdic2 = %@", mdic2);
        NSLog(@"dic1 = %@", dic1);
        NSLog(@"dic2 = %@", dic2);
2014-01-31 22:08:01.617 Dictionary[448:303] set new object for key
2014-01-31 22:08:01.618 Dictionary[448:303] mdic1 = {
    key1 = "new obj1";
    key2 = obj2;
    key3 = obj3;
}
2014-01-31 22:08:01.619 Dictionary[448:303] mdic2 = {
    key1 = obj1;
    key2 = obj2;
    key3 = obj3;
}
2014-01-31 22:08:01.619 Dictionary[448:303] dic1 = {
    key1 = obj1;
    key2 = obj2;
    key3 = obj3;
}
2014-01-31 22:08:01.619 Dictionary[448:303] dic2 = {
    key1 = obj1;
    key2 = obj2;
    key3 = obj3;
}

这里只是修改了mdic1的索引key1中保存的内存地址,并不会对其他引用所指向的对象造成影响。

(3)在字典中添加新的key-value对:

// add new key-value
        NSMutableString *obj4 = [NSMutableString stringWithString:@"obj4"];
        [mdic1 setObject:obj4 forKey:@"key4"];
        NSLog(@"add new key-value");
        NSLog(@"mdic1 = %@", mdic1);
        NSLog(@"mdic2 = %@", mdic2);
        NSLog(@"dic1 = %@", dic1);
        NSLog(@"dic2 = %@", dic2);
2014-01-31 22:12:14.678 Dictionary[466:303] add new key-value
2014-01-31 22:12:14.679 Dictionary[466:303] mdic1 = {
    key1 = obj1;
    key2 = obj2;
    key3 = obj3;
    key4 = obj4;
}
2014-01-31 22:12:14.679 Dictionary[466:303] mdic2 = {
    key1 = obj1;
    key2 = obj2;
    key3 = obj3;
}
2014-01-31 22:12:14.679 Dictionary[466:303] dic1 = {
    key1 = obj1;
    key2 = obj2;
    key3 = obj3;
}
2014-01-31 22:12:14.680 Dictionary[466:303] dic2 = {
    key1 = obj1;
    key2 = obj2;
    key3 = obj3;
}

现在为mdic1对应的字典添加新的key-value对,这不会影响到其他字典指针,所以输出不受影响。

小结:

1.浅复制复制的是对象的引用,对指针的修改并不会影响到指向的对象,更不会影响到其他指针。 深复制复制的是对象的内容,对对象的操作修改将影响到所有指向该对象的引用。

2.NSMutableArray和NSMutableDictionary的复制是浅复制,NSMutableString的复制是深复制。由于数组或字典中对象数目或大小可能非常大,所以对对象的复制可能引起大量开销,因此这里只复制引用可以节省开销。

时间: 2024-10-12 04:23:26

复制对象 copy 与mutable copy的相关文章

复制对象(一)copy和mutableCopy方法

本文转载至 http://www.tuicool.com/articles/Fn6rMn CSDN博客原文  http://blog.csdn.net/u010962810/article/details/18887841 通过copy方法可以创建可变对象或不可变对象的不可变副本,对于不可变副本,其对象的值不可以改变. 通过mutableCopy方法可以创建可变对象或不可变对象的可变副本,对于可变副本其对象是可变的. 复制分为浅复制和深复制两种:浅复制只是复制对象的引用,并没有复制对象的具体内容

Objective-C 谈谈深浅拷贝,copy和mutable copy都不是完全拷贝

(一)字符串中的指针赋值,copy和mutablecopy NSString和NSString (1)指针赋值 肯定指向同一个字符串地址. (2)copy(和直接指向一样) NSString *[email protected]"aaa"; NSString *str2=[str1 copy]; NSLog(@"str1:%p----str2:%p",&str1,&str2);//指针地址输出,不一样,说明指针新建了 NSLog(@"str

python中的深copy和浅copy

bytes Python bytes/str bytes 在Python3中作为一种单独的数据类型,不能拼接,不能拼接,不能拼接 >>> '€20'.encode('utf-8') b'\xe2\x82\xac20' >>> b'\xe2\x82\xac20'.decode('utf-8') '€20' 解码 >>> b'\xa420'.decode('windows-1255') '?20' 深copy和浅copy 深copy新建一个对象重新分配内存

正确地复制对象--oeprator=与copy构造函数

额,这个名字有点怪怪的=_= ok,下面进入正题,为了演示方便,代码只写出简略的部分. copy构造函数 class Base { public: Base() {} Base(const Base& ) { cout<<"Base copy "<<endl; } }; class Derived: public Base { public: Derived() {} Derived(const Derived& ind) {} }; 重点关注一

Python3标准库:copy复制对象

1. copy复制对象 copy模块包括两个函数copy()和deepcopy(),用于复制现有的对象. 1.1 浅副本 copy()创建的浅副本(shallow copy)是一个新容器,其中填充了原对象内容的引用.建立list对象的一个浅副本时,会构造一个新的list,并将原对象的元素追加到这个list. import copy import functools @functools.total_ordering class MyClass: def __init__(self, name):

copy构造与copy复制

“copy构造”与“copy复制”误区:----“=”语法也可以用来调用copy构造函数: 如:Constr object3 = object1; 区别在于:如果定义一个新的对象(如Constr object3),一定会有个构造函数被调用,不可能调用复制操作. 如果没有新对象被定义(如object1 = object2;),不会有构造函数被调用,你们当然是“copy复制”操作被调用! 示例代码: #include<iostream>#include<vector>#include&

copy&amp;mutableCopy 浅拷贝(shallow copy)深拷贝 (deep copy)

本文来自 这里,原文作者微博MicroCai 概念 对象拷贝有两种方式:浅复制和深复制.顾名思义,浅复制,并不拷贝对象本身,仅仅是拷贝指向对象的指针:深复制是直接拷贝整个对象内存到另一块内存中. 一图以蔽之 再简单些说:浅复制就是指针拷贝:深复制就是内容拷贝. 集合的浅复制 (shallow copy) 集合的浅复制有非常多种方法.当你进行浅复制时,会向原始的集合发送retain消息,引用计数加1,同时指针被拷贝到新的集合. 现在让我们看一些浅复制的例子: NSArray *shallowCop

Shallow copy and Deep copy

一.来自wikipidia的解释: Shallow copy One method of copying an object is the shallow copy. In that case a new object B is created, and the fields values of A are copied over to B. This is also known as a field-by-field copy,field-for-field copy, or field co

条款12:复制对象时勿忘其每一个成分

对象复制操作operator=或copy构造函数,一定要记得复制对象每一个成份,特别是base class的成分: 注意: