iOS中關(guān)于深拷貝和淺拷貝的理解

在以前的理解當(dāng)中 copymutableCopy 對(duì)應(yīng)的解釋分別是 深拷貝淺拷貝, 但是這樣的理解是不對(duì)的, 在查找資料后, 理解如下:

所有系統(tǒng)容器類的copy或mutableCopy方法,都是淺拷貝

系統(tǒng)的容器類包括 比如NSArray,NSMutableArray,NSDictionary,NSMutableDictionary 等.

但是很多文章, 或者視頻教學(xué)里的講解并非如此. 然而在找資料的過程當(dāng)中, 我看到了這一段官方的文檔

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.

大概理解一下

有兩種類型的對(duì)象拷貝,淺拷貝和深拷貝。正常的拷貝,生成一個(gè)新的容器,但卻是和原來的容器共用內(nèi)部的元素,這叫做淺拷貝。深拷貝不僅生成新的容器,還生成了新的內(nèi)部元素。

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.

以上兩段解釋意思基本一致

代碼可自行驗(yàn)證

NSStringNSMutableString 這兩個(gè)并不是容器類, 所以談不上 深拷貝淺拷貝

如果要實(shí)現(xiàn)深拷貝, 則用系統(tǒng)方法:
initWithArray:copyItems:

比如:
NSArray *deepCopyArray = [[NSArray alloc] initWithArray:someArray copyItems:YES];

當(dāng)然可以自定義方法

- (NSArray *)test_deepCopy {
    NSMutableArray *array = [NSMutableArray array];
    for (id element in self) {
        id copyElement = nil;
        if ([element respondsToSelector:@selector(test_deepCopy)]) {
            copyElement = [element test_deepCopy];
        }
        else if ([element respondsToSelector:@selector(copyWithZone:)]) {;
            copyElement = [element copy];
        }
        else {
            copyElement = element;
        }
        [array addObject:copyElement];
    }
    NSArray *result = [NSArray arrayWithArray:array];
    return result;
}

- (NSMutableArray *)test_mutableDeepCopy {
    NSMutableArray *array = [NSMutableArray array];
    for (id element in self) {
        id copyElement = nil;
        if ([element respondsToSelector:@selector(test_mutableDeepCopy)]) {
            copyElement = [element test_mutableDeepCopy];
        }
        else if ([element respondsToSelector:@selector(mutableCopyWithZone:)]) {
            copyElement = [element mutableCopy];
        }
        else if ([element respondsToSelector:@selector(copyWithZone:)]) {
            copyElement = [element copy];
        }
        else {
            copyElement = element;
        }
        [array addObject:copyElement];
    }
    return array;
}

總結(jié):
所有系統(tǒng)容器類的copy或mutableCopy方法,都是淺拷貝
系統(tǒng)的容器類包括

參考博客

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容