main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
//-----------第1种归档方式---------
//1.使用NSKeyedArchiver 归档对象到文件(对象序列化,持久化)
NSArray* arrays = [[NSArray alloc]initWithObjects:@"111",@"222", nil];
NSString* userPath = NSHomeDirectoryForUser(@"3g2win");
NSLog(@"userPath=%@",userPath);
NSString* bakFilePath = [userPath stringByAppendingFormat:@"/test.txt"];
NSLog(@"bakFilePath=%@",bakFilePath);
NSLog(@"归档前的数组:\n\n%@",arrays);
//归档
if ([NSKeyedArchiver archiveRootObject:arrays toFile:bakFilePath]){
NSLog(@"归档成功...\n\n");
}else {
NSLog(@"归档失败...\n\n");
}
//2.使用NSKeyedUnarchiver 解归档文件到对象(反序列化)
//解归档
NSArray* srcArr = [NSKeyedUnarchiver unarchiveObjectWithFile:bakFilePath];
NSLog(@"解归档后的数组:\n\n%@",srcArr);
//------------第2种归档方式---------
//归档
NSMutableData* data = [NSMutableData alloc];
NSKeyedArchiver* archiver = [NSKeyedArchiver alloc];
[archiver initForWritingWithMutableData:data];
[archiver encodeObject:@"张三" forKey:@"name"];
[archiver encodeInt:25 forKey:@"age"];
[archiver encodeFloat:5200.5F forKey:@"money"];
[archiver finishEncoding];
[data writeToFile:@"/Users/3g2win/11111111111.txt" atomically:YES];
//解归档
NSMutableData* data2 = [NSMutableData dataWithContentsOfFile:@"/Users/3g2win/11111111111.txt"];
NSKeyedUnarchiver* unArchiver = [NSKeyedUnarchiver alloc];
[unArchiver initForReadingWithData:data2];
NSLog(@"name=%@",[unArchiver decodeObjectForKey:@"name"]);
NSLog(@"age=%d",[unArchiver decodeIntForKey:@"age"]);
NSLog(@"money=%f",[unArchiver decodeFloatForKey:@"money"]);
//-------------自定义对象的归档和解归档------------
Person* zhao6 = [[Person alloc] initWithName:@"赵六" withAge:18];
[zhao6 display];
//归档
[NSKeyedArchiver archiveRootObject:zhao6 toFile:@"/Users/3g2win/zhao6.txt"];
//解档
Person* newZhao6 = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/3g2win/zhao6.txt"];
[newZhao6 display];
}
return 0;
}
Person.h
#import <Foundation/Foundation.h>
//必须实现NSCoding协议才能够归档解归档自定义类
@interface Person : NSObject <NSCoding>
{
NSString* name;
int age;
}
@property (nonatomic,assign) NSString* name;
@property (nonatomic,assign) int age;
- (id) initWithName:(NSString*) _name withAge:(int) _age;
- (void) display;
@end
Person.m
#import "Person.h"
#define NAME @"NAME"
#define AGE @"AGE"
@implementation Person
@synthesize name;
@synthesize age;
- (id) initWithName:(NSString*) _name withAge:(int) _age {
if (self = [super init]) {
self.name = _name;
self.age = _age;
}
return self;
}
- (void) display {
NSLog(@"Person Name : %@\t Age :%d",name,age);
}
//归档编码
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:name forKey:NAME];
[aCoder encodeInt:age forKey:AGE];
}
//解归档解码
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:NAME];
self.age = [aDecoder decodeIntForKey:AGE];
}
return self;
}
@end