深复制与浅复制

2017-12-01  本文已影响10人  攻克乃还_

小编致力于用精简的语言说明不精简的问题

一、概念

二、对象拷贝遵循规则

无论是集合类型NSArray、NSDictionary、NSSet ...,还是非集合类型NSString, NSNumber ... 对象,调用copy、mutableCopy方法时:

注:下面代码是对的,只是改变了str对象的指针

NSString *str = @"string";
str = @"newString";

三、集合拷贝遵循规则

3.1.集合的浅复制
NSArray *shallowCopyArray = [someArray copyWithZone:nil];
NSSet *shallowCopySet = [NSSet mutableCopyWithZone:nil];
NSDictionary *shallowCopyDict = [[NSDictionary alloc] initWithDictionary:someDictionary copyItems:NO];
3.2.集合的深复制

方法1:initWithArray:copyItems:

NSDictionary shallowCopyDict = [[NSDictionary alloc] initWithDictionary:someDictionary copyItems:YES];

方法2:归档之后解挡

NSArray *trueDeepCopyArray = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:oldArray]];
3.3.集合的单层深复制 (one-level-deep copy)

在多层数组中,对第一层进行内容拷贝,其它层进行指针拷贝

参考资料:
深复制与浅复制解析

上一篇下一篇

猜你喜欢

热点阅读