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

iOS-NSCoding归档

2016-02-23 17:36 543 查看
归档比NSUserdefaults多了存储对象

例子:新建了一个学生类 .h文件

#import <Foundation/Foundation.h>

@interface ybStudent : NSObject <NSCoding>//遵守协议

/**名字*/
@property (nonatomic,copy)NSString *name;
/**年龄*/
@property (nonatomic,assign)int age;
/**身高*/
@property (nonatomic,assign)double height;

@end

学生类 .m文件
#import "ybStudent.h"

@implementation ybStudent

/**
* 将某个对象写入文件时会调用
* 在这个方法中说说清楚哪些属性需要存储
*/
- (void)encodeWithCoder:(NSCoder *)aCoder
{
//存储的类型需要和属性类型匹配
[aCoder encodeObject:self.name forKey:@"myName"];
[aCoder encodeDouble:self.height forKey:@"myHeight"];
[aCoder encodeInt:self.age forKey:@"myAge"];
}

/**
* 从文件中解析对象时会调用
* 在这个方法中说清楚哪些属性需要读取
*/
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"myName"];
self.age = [aDecoder decodeIntForKey:@"myAge"];
self.height = [aDecoder decodeDoubleForKey:@"myHeight"];
}
return self;
}

@end

控制器里面两个按钮,分别为写入数据和读取数据
- (IBAction)save:(UIButton *)sender
{
ybStudent *student = [[ybStudent alloc] init];
student.name = @"Tom";
student.age = 18;
student.height = 1.75;

//获得Documents的全路径
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSString *path = [documentPath stringByAppendingPathComponent:@"student.data"];

//将对象归档
[NSKeyedArchiver archiveRootObject:student toFile:path];
}

- (IBAction)read:(UIButton *)sender
{
//从文件中读取
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

NSString *path = [documentPath stringByAppendingPathComponent:@"student.data"];

ybStudent *student = [NSKeyedUnarchiver unarchiveObjectWithFile:path];

NSLog(@"name---%@,age---%d,height---%f",student.name,student.age,student.height);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS NSCoding 归档 存储