【Demo 0025】FoundationKit 深浅拷贝
一、深浅拷贝
浅复制 -- 一个对象赋值给另一个对象,实际上就是指针复制,当一个内容发生变化时别一个也会发生变化;
深复制 -- 一个对象内容拷贝给别一个对象,深复制后两个对象都是相互独立的,互不影响;
二、自定义类型实现深拷贝
实现深拷贝方法:主要实现NSCopying协议的copyWithZone方法, 代码模型
@interface className : NSObject<NSCopying>
@property (nonatomic, copy) NSString* name;
-(id) copyWithZone: (NSCopying)zone;
@end
@implementation
(id) copyWithZone: (NSCopying)zone
{
内成员深复制
}
@end
三、练习代码
@interface Book : NSObject<NSCopying>
{
NSMutableString* _name;
NSString* _isbn;
NSUInteger _price;
}
@property(nonatomic, copy) NSString* _name;
@property(nonatomic, copy) NSString* _isbn;
@property(nonatomic, assign) NSUInteger _price;
-(id) init;
-(void) print:(NSString*)prompt;
-(id) copyWithZone:(NSZone*)zone;
@end
@implementation Book
@synthesize _name;
@synthesize _isbn;
@synthesize _price;
-(id) init
{
if (self = [super init])
{
_name = @"";
_isbn = @"";
_price = 0;
}
returnself;
}
-(void) print:(NSString*)prompt
{
NSLog(@"\n%@\nname: %@\nisbn: %@\nprice: %lu", prompt, _name, _isbn, _price);
}
-(id) copyWithZone:(NSZone*)zone
{
Book* book = [[Book allocWithZone:zone]init];
[book set_name:_name];
[book set_isbn:_isbn];
[book set_price:_price];
return book;
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
Book* book = [[Book alloc]init];
NSMutableString* name = [NSMutableStringstringWithString:@"ztercel objective-c"];
[book set_name:name];
[book set_isbn:@"978-7-126-14974-10"];
[book set_price:89.0];
[book print:@"create book:"];
[name appendFormat:@"i do"];
[book print:@"after modify name source data, book data:"];
Book* book2 = [book copy]; // book;
[book2 set_name:@"objective-c programming"];
[book2 set_price:100];
[book2 print:@"book2 value: "];
[book print:@"book value: "];
}
演示实例
浙公网安备 33010602011771号