objective-c - NSArray *array = otherarray;是深拷贝还是浅拷贝?该怎么理解
PHPz
PHPz 2017-04-24 09:11:20
0
2
485

NSArray *array = [[NSArray alloc] initWithObjects:@23, @"re", nil] ;
NSArray *arr2 = array;
NSLog(@"%lu",(unsigned long)[array retainCount]);
NSLog(@"%lu",(unsigned long)[arr2 retainCount]);

结果是 1,1


NSArray *array = [[NSArray alloc] initWithObjects:@23, @"re", nil] ;
NSArray *arr2 = [array copy];
NSLog(@"%lu",(unsigned long)[array retainCount]);
NSLog(@"%lu",(unsigned long)[arr2 retainCount]);

结果是 2,2


NSArray *array = [[NSArray alloc] initWithObjects:@23, @"re", nil] ;
NSArray *arr2 = [array mutbaleCopy];
NSLog(@"%lu",(unsigned long)[array retainCount]);
NSLog(@"%lu",(unsigned long)[arr2 retainCount]);

结果是1,1

所以应该怎么理解???

PHPz
PHPz

学习是最好的投资!

reply all(2)
PHPzhong
NSArray *arr2 = array;

The above code is neither a deep copy nor a shallow copy. It is just a pointer assignment. They point to the same memory.


NSArray *arr2 = [array copy];

The above code is theoretically array 创建了一份浅拷贝,可实际上并没有发生任何拷贝,仅仅做了一次 retain.

This is because NSArray 是一个不可被修改的只读数组,它在实现 NSCopying protocol 的时候很机(tou)智(lan)的仅仅做了一次 retain 而没有创建任何新对象,所以造成 arrayarr2 the reference counts all become 2, which is somewhat counterintuitive.

Note that at this time arrayarr2 points to the same memory, which can be clearly seen by printing the pointer address.


NSArray *arr2 = [array mutableCopy];

The above code, mutableCopy 返回的是一个 NSMutableArray,这时候 NSArray 没什么巧可取,就是老老实实的创建了一个新的 NSMutableArray 对象,array 指向 NSArrayarr2 指向新创建的 NSMutableArray, so the reference count is all 1.


Back to deep copy and shallow copy, for a container, if the objects in the container only increase the reference count when copying, then it is a shallow copy; otherwise, if a new object is created for each object, then it is a deep copy.

The questioner should use NSMutableArray 来尝试才能得到清晰正确的结果,NSArray This kind of immutable container cannot see the desired effect.

By the way, NSMutableArraycopy is a shallow copy.

洪涛

As an aside, breakpoints, LLDB debugging or printing and observing memory addresses can help us better understand the mechanism here.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template