关于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里面存的是指针,它就会把指针值做深拷贝,等于是后面的数组跟前面的数组,存的指针值是一样的,但是指针指向的内容不做深拷贝,所以改了指针指向的内容,会同时影响两个数组。

你可能感兴趣的:(关于copy)