@autoreleasepool {
NSString *homeDictory=NSHomeDirectory();
NSArray *array=[NSArray arrayWithObjects:@"one",@"two",@"three",nil];
NSString *homePath=[homeDictory stringByAppendingPathComponent:@"Desktop/test.archive"];
if(![NSKeyedArchiver archiveRootObject:array toFile:homePath])
{
NSLog(@"歸檔失敗");
}else
{
NSArray *data=[NSKeyedUnarchiver unarchiveObjectWithFile:homePath];
NSLog(@"%@",data);
}
NSLog(@"Hello, World!");
}
第四、復雜的內容歸檔 使用NSData實例作為歸檔的存儲數據,添加歸檔的內容(設置key和value),完成歸檔,將歸檔內容存入磁盤 解歸檔步驟:從磁盤讀取文件,生成NSData實例,根據data實例創建或初始化歸檔實例,解歸檔,根據key訪問value的值
NSString *homeDictory=NSHomeDirectory();
NSString *homePath=[homeDictory stringByAppendingPathComponent:@"Desktop/usertest.archive"];
NSMutableData *data=[NSMutableData data];
NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
NSArray *nameArray=[NSArray arrayWithObjects:@"andy",@"yang", nil];
[archiver encodeInt:100 forKey:@"age"];
[archiver encodeObject:nameArray forKey:@"names"];
[archiver finishEncoding];
[archiver release];
if ([data writeToFile:homePath atomically:YES])
{
NSData *data2=[NSData dataWithContentsOfFile:homePath];
NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data2];
int age=[unarchiver decodeIntForKey:@"age"];
NSArray *array2=[unarchiver decodeObjectForKey:@"names"];
NSLog(@"%d",age);
NSLog(@"%@",array2);
[unarchiver release];
} else
{
NSLog(@"write to file wrong");
}
NSLog(@"Hello, World!");