iOS基础 归档和解归档

在iOS的实际开发中,我们有很多的地方会运用的数据缓存。数据缓存中用到的技术大概有SQLite,NSUserDefaults,coreDat等。还有一些第三方的基本是对上面的封装。我这里介绍的是最基础的归档.
1.先建立一个person类,并且专寻NSCoding协议:

@interface Person : NSObject<NSCoding>
@property(nonatomic,strong)NSString *name;//名字
@property(nonatomic,assign)NSInteger age;//年龄
@property(nonatomic,strong)NSString *sex;//性别
//初始化方法
-(id)initWithName:(NSString *)name Age:(NSInteger)age Sex:(NSString *)sex;
#import "Person.h"

@implementation Person


-(id)initWithName:(NSString *)name Age:(NSInteger)age Sex:(NSString *)sex{
   self=[super init];
    if (self) {
        self.name=name;
        self.age=age;
        self.sex=sex;
    }
    return self;

}
/**
 *  归档
 *
 *  @param aCoder
 */
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
    [aCoder encodeObject:self.sex forKey:@"sex"];

}
/**
 *  解归档
 *
 */
-(id)initWithCoder:(NSCoder *)aDecoder{
    self=[super init];
    if (self) {
        self.name=[aDecoder decodeObjectForKey:@"name"];
        self.age=[aDecoder decodeIntegerForKey:@"age"];
        self.sex=[aDecoder decodeObjectForKey:@"sex"];
    }
    return self;
}

@end

2.现在建立界面,模拟保存name,age,sex三个属性 如图:

这里写图片描述

4.在控制器里面调用归档和解归档就可以了

#import "ViewController.h"
#import "Person.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self coder];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)coder{
    //解挡
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"person.text"];
    Person *person=[NSKeyedUnarchiver unarchiveObjectWithFile:path];

    NSLog(@"name:%@ age:%ld sex:%@",person.name,person.age,person.sex);
    self.nameTextField.text=person.name;
    self.ageTextField.text=[NSString stringWithFormat:@"%ld",(long)person.age ];
    self.sexTextField.text=person.sex;


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)clickOKBtn:(id)sender {

     Person *p1=[[Person alloc]initWithName:self.nameTextField.text Age:[self.ageTextField.text integerValue] Sex:self.sexTextField.text];
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *path=[docPath stringByAppendingPathComponent:@"person.text"];
    [NSKeyedArchiver archiveRootObject:p1 toFile:path];
}
@end

这里写图片描述

最后,当你输入name,age,sex点击保存之后,退出程序,person的属性依然保存在沙盒里面。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值