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
The above code is neither a deep copy nor a shallow copy. It is just a pointer assignment. They point to the same memory.
The above code is theoretically
array
创建了一份浅拷贝,可实际上并没有发生任何拷贝,仅仅做了一次retain
.This is because
NSArray
是一个不可被修改的只读数组,它在实现NSCopying
protocol 的时候很机(tou)智(lan)的仅仅做了一次retain
而没有创建任何新对象,所以造成array
和arr2
the reference counts all become 2, which is somewhat counterintuitive.Note that at this time
array
和arr2
points to the same memory, which can be clearly seen by printing the pointer address.The above code,
mutableCopy
返回的是一个NSMutableArray
,这时候NSArray
没什么巧可取,就是老老实实的创建了一个新的NSMutableArray
对象,array
指向NSArray
,arr2
指向新创建的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,
NSMutableArray
的copy
is a shallow copy.As an aside, breakpoints, LLDB debugging or printing and observing memory addresses can help us better understand the mechanism here.