關於深拷貝淺拷貝

There are two kinds of object copying: shallow copies and deep copies. The normal copy is a shallow copy that produces a new collection that shares ownership of the objects with the original. Deep copies create new objects from the originals and add those to the new collection.
以上三句出自於蘋果官方文檔 Collections.pdf。數組

意思大體以下:atom

有兩種類型的對象拷貝,淺拷貝和深拷貝。正常的拷貝,生成一個新的容器,但倒是和原來的容器共用內部的元素,這叫作淺拷貝。深拷貝不只生成新的容器,還生成了新的內部元素。spa

In the case of these objects, a shallow copy means that a new collection object is created, but the contents of the original collection are not duplicated—only the object references are copied to the new container. 
A deep copy duplicates the compound object as well as the contents of all of its contained objects.
以上兩句出自於蘋果官方文檔 CFMemoryMgmt.pdf。code

OK,有官方文檔爲證。淺拷貝複製容器,深拷貝複製容器及其內部元素orm

淺copy示例:對象

NSMutableArray *newArray = [self.dataArr mutableCopy];
    WeekModel *model = [newArray objectAtIndex:indexPath.row];
    
    if ([model.isCheck isEqualToString:@"1"]) {
        model.isCheck = @"0";
    } else {
        model.isCheck = @"1";
    }
    ChooseCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setCheckd:[self.dataArr objectAtIndex:indexPath.row]];

//如上代碼雖然使用的是mutableCopy,但依舊是淺copy,與使用copy意義是同樣的其實;所以僅僅是copy的數組容器,並無開闢新空間容納數組內的數據,所以newArray中數據更改時,對應的self.dataArr的數據也是在更改;

深copy示例:blog

  //深copy
NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:self.dataArr copyItems:YES]; WeekModel *model = [newArray objectAtIndex:indexPath.row]; if ([model.isCheck isEqualToString:@"1"]) { model.isCheck = @"0"; } else { model.isCheck = @"1"; } // 該代碼就是self.dataArr替換更改過的model [self.dataArr replaceObjectAtIndex:indexPath.row withObject:model]; ChooseCell *cell = [tableView cellForRowAtIndexPath:indexPath]; [cell setCheckd:[self.dataArr objectAtIndex:indexPath.row]];

如上就是深copy的實現方式,所以從新開闢新空間以供數組元素存儲,所以newArray中model發生改變時,並不會影響self.dataArr的數據。ip

不過使用深copy時須要注意一點:須要對自定義的model重寫copyWithZone:方法文檔

//.h文件
@interface
WeekModel : NSObject @property (strong, nonatomic) NSString *weekId; @property (strong, nonatomic) NSString *weekName; @property (assign, nonatomic) NSString *isCheck; - (instancetype)initWithId:(NSString *)weekId weekName:(NSString *)weekName isCheck:(NSString *)isCheck; - (id)copyWithZone:(NSZone *)zone;
//.m文件
- (instancetype)initWithId:(NSString *)weekId weekName:(NSString *)weekName isCheck:(NSString *)isCheck { self = [super init]; if (self) { self.weekId = weekId; self.weekName = weekName; self.isCheck = isCheck; } return self; } - (id)copyWithZone:(NSZone *)zone { WeekModel *model = [[WeekModel allocWithZone:zone] init]; model.weekId = self.weekId; model.weekName = self.weekName; model.isCheck = self.isCheck; return model; }

 

最後來總結一下:it

全部系統容器類的copy或mutableCopy方法,都是淺拷貝!!!

淺拷貝複製容器,深拷貝複製容器及其內部元素

相關文章
相關標籤/搜索