您的位置:首页 > 运维架构

关于copy

2015-07-02 00:00 316 查看
摘要: 深拷贝,浅拷贝 copy

NSMutableArray* a = [NSMutableArray arrayWithObjects:@"123",@"345", nil];

NSMutableArray* b = [NSMutableArray arrayWithObjects:@"xyz",@"abc", nil];

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

NSArray *d = [c copy];

for (NSArray* arr in d) {

for (NSString* s in arr) {

NSLog(@"element: %@", s);

}

}

a[0] = @"haha";

for (NSArray* arr in d) {

for (NSString* s in arr) {

NSLog(@"element: %@", s);

}

}

结果:

2015-07-02 13:53:00.112 Test[15564:327797] element: 123

2015-07-02 13:53:00.112 Test[15564:327797] element: 345

2015-07-02 13:53:00.112 Test[15564:327797] element: xyz

2015-07-02 13:53:00.112 Test[15564:327797] element: abc

2015-07-02 13:53:00.112 Test[15564:327797] element: haha

2015-07-02 13:53:00.112 Test[15564:327797] element: 345

2015-07-02 13:53:00.112 Test[15564:327797] element: xyz

2015-07-02 13:53:00.113 Test[15564:327797] element: abc

******************************************

NSMutableArray* a = [NSMutableArray arrayWithObjects:@"123",@"345", nil];

NSMutableArray* b = [NSMutableArray arrayWithObjects:@"xyz",@"abc", nil];

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

// SEE the difference.

NSArray *d = [c copyDeeply];

for (NSArray* arr in d) {

for (NSString* s in arr) {

NSLog(@"element: %@", s);

}

}

a[0] = @"haha";

for (NSArray* arr in d) {

for (NSString* s in arr) {

NSLog(@"element: %@", s);

}

}

结果:

2015-07-02 13:53:47.111 Test[15596:328543] element: 123

2015-07-02 13:53:47.112 Test[15596:328543] element: 345

2015-07-02 13:53:47.112 Test[15596:328543] element: xyz

2015-07-02 13:53:47.112 Test[15596:328543] element: abc

2015-07-02 13:53:47.112 Test[15596:328543] element: 123

2015-07-02 13:53:47.112 Test[15596:328543] element: 345

2015-07-02 13:53:47.112 Test[15596:328543] element: xyz

2015-07-02 13:53:47.112 Test[15596:328543] element: abc

copy只做第一级的深拷贝。 如果array里面存的是指针,它就会把指针值做深拷贝,等于是后面的数组跟前面的数组,存的指针值是一样的,但是指针指向的内容不做深拷贝,所以改了指针指向的内容,会同时影响两个数组。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: