在以前的理解當(dāng)中 copy 和 mutableCopy 對(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)證
而 NSString 和 NSMutableString 這兩個(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)的容器類包括