Deep Copy and Shallow Copy

后端 未结 4 1154
半阙折子戏
半阙折子戏 2020-12-07 23:36

I have read the answer for difference between deep copy and shallow copy from the post, What is the difference between a deep copy and a shallow copy? . Now I got some doubt

4条回答
  •  -上瘾入骨i
    2020-12-08 00:14

    First of all, NSArray's don't have a deep copy function. However, you can make a deep copy function by doing the following:

    @interface NSArray(deepCopy)
    
    -(NSArray *) deepCopy;
    
    @end
    
    @implementation
    
    -(NSArray *) deepCopy
    {
        NSMutableArray *ret = [NSMutableArray array];
    
        for (id val in self)
        {
            if ([val conformsToProtocol:@protocol(NSCopying)])
            { 
                [ret addObject:[val copy]];
            }
            else
            {
               [ret addObject:val];
            }
        }
    
        return ret;
    }
    
    @end 
    

    Second of all, newArray = oldArray does not copy the array. It simply makes newArray point to the array that oldArray points to.

    Third, +arrayWithArray: does a shallow copy of the array, meaning the individual objects are NOT copied.

提交回复
热议问题