在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的属性依然保存在沙盒里面。