众所周知:浅复制就是指针拷贝(拷贝指向对象的指针);深复制就是内容拷贝(直接拷贝整个对象内存到另一块内存中)。
不管深复制还是浅复制,都是一级的拷贝;而实际项目应用中,数据往往比较复杂,需要拷贝集合里的所有层级内容。这就需要使用递归思路实现深拷贝。废话不多说,直接上代码。
NSDictionary 深拷贝
-(NSDictionary*)dl_deepCopy{
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:[self count]];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
id item = obj;
if ([item respondsToSelector:@selector(dl_deepCopy)]) {
item = [item dl_deepCopy];
} else {
item = [item copy];
}
if (item && key) {
[dic setObject:item forKey:key];
}
}];
return [NSDictionary dictionaryWithDictionary:dic];
}
-(NSMutableDictionary*)dl_mutableDeepCopy{
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:[self count]];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
id item = obj;
if ([item respondsToSelector:@selector(dl_mutableDeepCopy)]){
item = [item dl_mutableDeepCopy];
} else if ([item respondsToSelector:@selector(mutableCopyWithZone:)]) {
item = [item mutableCopy];
} else {
item = [item copy];
}
if (item && key) {
[dic setObject:item forKey:key];
}
}];
return dic;
}
NSArray 深拷贝
-(NSArray*)dl_deepCopy{
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[self count]];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
id item = obj;
if ([item respondsToSelector:@selector(dl_deepCopy)]) {
item = [item dl_deepCopy];
} else {
item = [item copy];
}
if (item) {
[array addObject:item];
}
}];
return [NSArray arrayWithArray:array];
}
-(NSMutableArray*)dl_mutableDeepCopy{
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[self count]];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
id item = obj;
if ([item respondsToSelector:@selector(dl_mutableDeepCopy)]){
item = [item dl_mutableDeepCopy];
} else if ([item respondsToSelector:@selector(mutableCopyWithZone:)]) {
item = [item mutableCopy];
} else {
item = [item copy];
}
if (item) {
[array addObject:item];
}
}];
return array;
}
网友评论