search

Home  >  Q&A  >  body text

objective-c - NSArray *array = otherarray;是深拷贝还是浅拷贝?该怎么理解


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

所以应该怎么理解???

PHPzPHPz2766 days ago490

reply all(2)I'll reply

  • PHPz

    PHPz2017-04-24 09:13:20

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-24 09:13:20

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

    reply
    0
  • Cancelreply