iOS-NSCoding归档

归档比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);
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值