iOS深复制和浅复制
iOS深复制和浅复制
浅复制示例代码:
NSMutableArray *mArray = [NSMutableArray arrayWithObjects: [NSMutableString stringWithString: @"origionA"], [NSMutableString stringWithString: @"origionB"], [NSMutableString stringWithString: @"origionC"], nil]; NSMutableArray *mArrayCopy = [mArray mutableCopy]; NSMutableString *string = [mArray objectAtIndex:0]; [string appendString:@"Append"]; [mArrayCopy removeObjectAtIndex:1]; NSLog(@"object.name = %@",mArray); NSLog(@"object.name = %@",mArrayCopy);
打印结果:
2015-04-23 15:18:15.151 AppTest[14507:122304] object.name = (
origionAAppend,
origionB,
origionC
)
2015-04-23 15:18:15.151 AppTest[14507:122304] object.name = (
origionAAppend,
origionC
)
说明:
Foundation类实现了名为copy和mutableCopy的方法,可以使用这些方法创建对象的副本,通过实现一个符合
然而Foundation类的copy和mutableCopy方法,默认情况下只是对对象创建的一个新的引用,他们都指向同一块内存,也就是浅复制。因此就会出现上面的结果。
@protocol NSCopying - (id)copyWithZone:(NSZone *)zone; @end @protocol NSMutableCopying - (id)mutableCopyWithZone:(NSZone *)zone; @end
深复制示例代码:
@interface DemoObject : NSObject@property (strong, nonatomic) NSString *name; @end @implementation DemoObject - (id)copyWithZone:(NSZone *)zone { DemoObject* object = [[[self class] allocWithZone:zone]init]; return object; } @end
NSMutableArray *mArray = [NSMutableArray arrayWithObjects: [NSMutableString stringWithString: @"origionA"], [NSMutableString stringWithString: @"origionB"], [NSMutableString stringWithString: @"origionC"], nil]; NSMutableArray *mArrayCopy = [mArray mutableCopy]; NSMutableString *string = [mArray objectAtIndex:0]; [string appendString:@"Append"]; [mArrayCopy removeObjectAtIndex:1]; NSLog(@"object.name = %@",mArray); NSLog(@"object.name = %@",mArrayCopy);
打印结果:
2015-04-23 15:18:15.150 AppTest[14507:122304] object.name = object
2015-04-23 15:18:15.151 AppTest[14507:122304] newObject.name = newObject
说明:
自定义类中,必须实现
参数zone与不同的存储区有关,你可以在程序中分配并使用这些存储区,只有在编写要分配大量内存的应用程序并且想要通过将空间分配分组到这些存储区中来优化内存分配时,才需要处理这些zone。可以使用传递给copyWithZone:的值,并将它传给名为allocWithZone:的内存分配方法。这个方法在指定存储区中分配内存。
相关文章
- 暂无相关文章
用户评论