集合的遞歸深拷貝
關(guān)于拷貝的一些概念在iOS集合的深復制與淺復制里 講得很清楚啦.
我在這里想說的是遞歸深拷貝:
copy只做第一級的深拷貝。 如果array里面存的是指針,它就會把指針值做深拷貝,等于是后面的數(shù)組跟前面的數(shù)組,存的指針值是一樣的,但是指針指向的內(nèi)容不做深拷貝,所以改了指針指向的內(nèi)容,會同時影響兩個數(shù)組。
如果需要每一層都深拷貝的話:
NSMutableArray* a = [NSMutableArray arrayWithObjects:@"123",@"345", nil];
NSMutableArray* b = [NSMutableArray arrayWithObjects:@"xyz",@"abc", nil];
NSArray *c = [NSArray arrayWithObjects:a, b, nil];
NSArray *d = [c copyDeeply]; // 深拷貝
for (NSArray* arr in d) {
for (NSString* s in arr) {
NSLog(@"element: %@", s);
}
}
a[0] = @"haha";
for (NSArray* arr in d) {
for (NSString* s in arr) {
NSLog(@"element: %@", s);
}
}
結(jié)果:
2017-04-05 11:26:23.688 Test[1341:101216] element: 123
2017-04-05 11:26:23.688 Test[1341:101216] element: 345
2017-04-05 11:26:23.688 Test[1341:101216] element: xyz
2017-04-05 11:26:23.688 Test[1341:101216] element: abc
2017-04-05 11:26:23.689 Test[1341:101216] element: 123
2017-04-05 11:26:23.689 Test[1341:101216] element: 345
2017-04-05 11:26:23.689 Test[1341:101216] element: xyz
2017-04-05 11:26:23.689 Test[1341:101216] element: abc
******************************************
NSArray 遞歸深拷貝
- (id)copyDeeply {
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[self count]];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
id item = obj;
if ([item respondsToSelector:@selector(copyDeeply)]) {
item = [item copyDeeply];
} else {
item = [item copy];
}
if (item) {
[array addObject:item];
}
}];
return [NSArray arrayWithArray:array];
}
- (id)mutableCopyDeeply {
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[self count]];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
id item = obj;
if ([item respondsToSelector:@selector(mutableCopyDeeply)]) {
item = [item mutableCopyDeeply];
} else if ([item respondsToSelector:@selector(mutableCopyWithZone:)]) {
item = [item mutableCopy];
} else {
item = [item copy];
}
if (item) {
[array addObject:item];
}
}];
return array;
}
NSDictionary 遞歸深拷貝
- (id)copyDeeply {
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:[self count]];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
id item = obj;
if ([item respondsToSelector:@selector(copyDeeply)]) {
item = [item copyDeeply];
} else {
item = [item copy];
}
if ( item && key ) {
[dic setObject:item forKey:key];
}
}];
return [NSDictionary dictionaryWithDictionary:dic];
}
- (id)mutableCopyDeeply {
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:[self count]];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
id item = obj;
if ([item respondsToSelector:@selector(mutableCopyDeeply)]) {
item = [item mutableCopyDeeply];
} else if ([item respondsToSelector:@selector(mutableCopyWithZone:)]) {
item = [item mutableCopy];
} else {
item = [item copy];
}
if ( item && key ) {
[dic setObject:item forKey:key];
}
}];
return dic;
}