//使用Foundation的归档功能来创建对象的深复制
例如:Person类
Person.h
@interface Person : NSObject <NSCoding>
@property (nonatomic,copy)NSString *name;
@property (assign)int age;
- (id)initWithName:(NSString *)name withAge:(int)age;
Person.m
- (id)initWithName:(NSString *)name withAge:(int)age{
if(self = [super init])
{
self.name = name;
self.age = age;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{ //NSCoding协议必须实现的方法
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInt:self.age forKey:@"age"];
}
- (id)initWithCoder:(NSCoder *)aDecoder{ //NSCoding协议必须实现的方法
if(self = [super init])
{
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntForKey:@"age"];
}
return self;
}
main函数
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray *mArray = [NSMutableArray array];
NSMutableString *str1 = [NSMutableString stringWithString:@"one"];
NSMutableString *str2 = [NSMutableString stringWithString:@"two"];
NSMutableString *str3 = [NSMutableString stringWithString:@"three"];
Person *person = [[Person alloc]initWithName:@"yangcw" withAge:22];
[mArray addObject:str1];
[mArray addObject:str2];
[mArray addObject:str3];
[mArray addObject:person];
//自定义类需要使用NSKeyedArchiver
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:mArray];
NSArray *dataArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[str1 appendString:@"ONE"];
NSLog(@"mArray = %@ 地址=%p",mArray,mArray);
NSLog(@"array = %@ 地址=%p",dataArray,dataArray);
//结果显示person地址和数组地址都不一样
}
return 0;
}
//输出
2014-08-02 09:13:08.551 ycw_0801_2[433:303] mArray = (
oneONE,
two,
three,
"<Person: 0x10010bde0>"
) 地址=0x10010bd30
2014-08-02 09:13:08.553 ycw_0801_2[433:303] array = (
one,
two,
three,
"<Person: 0x10010a520>"
) 地址=0x10010f9b0