代码改变世界

object-c中归档的用法

2013-05-04 23:05  甘超波  阅读(1417)  评论(0编辑  收藏  举报

 

下面是归档的例子

//
//  main.m
//  ArchiveDemo
//
//  Created by ganchaobo on 13-5-4.
//  Copyright (c) 2013年 ganchaobo. All rights reserved.
//

#import <Foundation/Foundation.h>
void archive1(){
    //******************************************归档第一种方法
    NSArray *arr=[NSArray arrayWithObjects:@"11",@"vv",@"tt", nil];
    //归档(即序列化)archiveRootObject
    NSString *path=@"/Users/ganchaobo/Desktop/archiver.text";
    BOOL iskeyedarchiver= [NSKeyedArchiver archiveRootObject:arr toFile:path];
    if(iskeyedarchiver){
        NSLog(@"archive success ");
    }
    //*******************************************对应的解归档
    NSArray *unarchivearr =[NSKeyedUnarchiver unarchiveObjectWithFile:path];
    NSLog(@"%@",unarchivearr);
}

void archive2(){
     //******************************************归档第2种方法
    NSString *path1=@"/Users/ganchaobo/Desktop/archiver1.text";
    NSMutableData *date=[NSMutableData data];
    //初始化时要把归档的内容放在date中
    NSArray *arr=[NSArray arrayWithObjects:@"yuwen",@"math", nil];
    NSKeyedArchiver *archive= [[[NSKeyedArchiver alloc] initForWritingWithMutableData:date]autorelease];
    //下面时把内容归档到一个date里面取
    [archive  encodeFloat:1.81 forKey:@"height"];
    [archive encodeObject:@"zs" forKey:@"name"];
    [archive encodeObject:@"23" forKey:@"age"];
    [archive encodeObject:arr forKey:@"kemu"];
    [archive finishEncoding];
    
    [date writeToFile:path1 atomically:YES];//此时date数据时归档后的数据,然后写入指定的文件
    //*******************************************对应的解归档
    NSData *date1=[NSData dataWithContentsOfFile:path1];//读取内容
   NSKeyedUnarchiver *unarchive= [[[NSKeyedUnarchiver alloc] initForReadingWithData:date1] autorelease];
    NSLog(@"%f",[unarchive decodeFloatForKey:@"height"]);
    NSLog(@"%@",[unarchive decodeObjectForKey:@"name"]);
     NSLog(@"%@",[unarchive decodeObjectForKey:@"age"]);
     NSLog(@"%@",[unarchive decodeObjectForKey:@"kemu"]);
}

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        archive2();
    }
    return 0;
}