您的位置:首页 > 移动开发 > IOS开发

iOS疯狂详解之复杂对象归档反归档

2015-09-15 13:20 561 查看
需求:对复杂对象进行归档 反归档

复杂对象:工程中 自定义的数据模型类 例如一个Person类

Person.h

//
//  Person.h
//  MySandBox
//
//  Created by long on 15/9/15.
//  Copyright (c) 2015年 WLong. All rights reserved.
//

#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding>
@property (nonatomic,retain) NSString *name;
@property (nonatomic,assign) NSInteger age;
@property (nonatomic,retain) NSData *data;
@end

//
// Person.m
// MySandBox
//
// Created by long on 15/9/15.
// Copyright (c) 2015年 WLong. All rights reserved.
//

#import "Person.h"

@implementation Person

- (void)dealloc
{
[_name release];
[super dealloc];
}

// 归档 进行编码
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeObject:self.data forKey:@"data"];

}

// 反归档 解码
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {

self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
self.data = [aDecoder decodeObjectForKey:@"data"];

}
return self;
}

@end

//  归档复杂对象
- (void)archive
{
// 获取Documents文件路径
#define kDocumentsPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]

Person *p = [[Person alloc] init];
p.name = @"wang";
p.age = 12;
//   UIImagePNGRepresentation([UIImage imageNamed:@"shen"])
//   将png图片 转化成data
p.data = UIImagePNGRepresentation([UIImage imageNamed:@"shen"]);

//  创建一个可变的DATA 进行对 复杂对象编码后的储存
NSMutableData *data = [NSMutableData data];

//  创建归档对象
NSKeyedArchiver *archive = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
//  进行归档
[archive encodeObject:p forKey:@"person"];
//  归档结束
[archive finishEncoding];

NSString *archivePath = [kDocumentsPath stringByAppendingPathComponent:@"savePerson"];
NSLog(@"%@",archivePath);

//  写入归档文件
[data writeToFile:archivePath atomically:YES];
[p release];
[archive release];

}
//  反归档
- (void)unarchive
{
NSString *archivePath = [kDocumentsPath stringByAppendingPathComponent:@"savePerson"];

//  按路径读取 归档的data文件
NSData *data = [NSData dataWithContentsOfFile:archivePath];

//  创建反归档对象
NSKeyedUnarchiver *aaa = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
//  取出归档的对象
Person *p = [aaa decodeObjectForKey:@"person"];

UIImage *image = [UIImage imageWithData:p.data];

NSLog(@"%@",p.name);
}


综述: 归档复杂对象时 需要遵守NSCoding协议 并实现起方法 对要归档的对象 进行编码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS开发 归档 反归档