首页 > 其他 > 详细

归档解档(文件写入与读取)

时间:2015-05-08 00:03:56      阅读:210      评论:0      收藏:0      [点我收藏+]
**第一种方式:对象单一**
//归档
-(void)NSKeyedArchiver{

    NSArray *array = [NSArray arrayWithObjects:@"L",@"J",@"F",nil];
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.LJF"];

    NSLog(@"%@", filePath);
    BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:filePath];
    if(success){
        NSLog(@"保存成功");
    }

}

//解档
-(void)NSKeyedUnarchiver{
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.LJF"];
    id array = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    NSLog(@"%@",array);

}
**第二种方式:对象多个**
//归档2

-(void)NSKeyedArchiverTwo{
    NSArray *array = [NSArray arrayWithObjects:@"L",@"J",@"F", nil];
    NSDictionary *dic = @{@"name":array};
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    //编码
    [archiver encodeObject:dic forKey:@"dic"];
    [archiver encodeObject:array forKey:@"array"];
    [archiver encodeInt:100 forKey:@"num"];
    [archiver encodeObject:@"LJF" forKey:@"name"];

    //完成编码,将上面的归档数据填充到data中,此时data中已经存储了归档对象的数据
    [archiver finishEncoding];

    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.LJF"];
    BOOL success = [data writeToFile:filePath atomically:YES];
    if(success){
        NSLog(@"归档成功");
    }

}


//解档2

-(void)NSKeyedUnarchiverTwo{
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"array.LJF"];
    //读取归档数据
    NSData *data = [[NSData alloc] initWithContentsOfFile:filePath];

    //创建解归档对象,对data中的数据进行解归档
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

    //解归档
    NSArray *array = [unarchiver decodeObjectForKey:@"array"];
    NSLog(@"%@",array);

    NSDictionary *dic  = [unarchiver decodeObjectForKey:@"dic"];
    NSLog(@"%@", dic);

    NSString *name = [unarchiver decodeObjectForKey:@"name"];
    NSLog(@"%@",name);

    int value =  [unarchiver decodeIntegerForKey:@"num"];
    NSLog(@"%d", value);



}

归档解档(文件写入与读取)

原文:http://blog.csdn.net/tubiebutu/article/details/45568307

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!