IOS s数据存储之归档解档

#import <Foundation/Foundation.h>

@interface Student : NSObject <NSCoding>;
@property(nonatomic,strong)NSString* name;
@property(nonatomic,assign)int age;
@property(nonatomic,copy)NSString* tel;

-(id)initWithName:(NSString*)name endAge:(int)age endTel:(NSString*)tel;

@end


#import "Student.h"

@implementation Student
@synthesize name=_name,tel=_tel,age=_age;
-(id)initWithName:(NSString *)name endAge:(int)age endTel:(NSString *)tel
{
    if (self=[super init]) {
        self.name=name;
        self.age=age;
        self.tel=tel;
    }
    return self;
}

-(void)encodeWithCoder:(NSCoder *)aCoder
{
    NSLog(@"编码中。。。。");
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInt:self.age forKey:@"age"];
    [aCoder encodeObject:self.tel forKey:@"tel"];
//    [aCoder encodeValueOfObjCType:@"" at:<#(const void *)#>]
    
    
    
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
    NSLog(@"解码中。。。。");
    self=[self initWithName:[aDecoder decodeObjectForKey:@"name"] endAge:[aDecoder decodeIntForKey:@"age"] endTel:[aDecoder decodeObjectForKey:@"tel"]];
    
    return self;
}

@end




#import "ViewController.h"
#import "Student.h"
@interface ViewController ()
{
    UITextField* _tf1;
    UITextField* _tf2;
    UITextField* _tf3;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self encodeStu];
    
    
    // Do any additional setup after loading the view, typically from a nib.
    // Dispose of any resources that can be recreated
    _tf1=[[UITextField alloc]initWithFrame:CGRectMake(20, 20, 200, 40)];
    
    _tf2=[[UITextField alloc]initWithFrame:CGRectMake(20, 100, 200, 40)];
    _tf2.keyboardType=UIKeyboardTypeDecimalPad;
    
    
    _tf3=[[UITextField alloc]initWithFrame:CGRectMake(20, 150, 200, 40)];
    
    _tf1.borderStyle=UITextBorderStyleRoundedRect;
    _tf2.borderStyle=UITextBorderStyleRoundedRect;
    _tf3.borderStyle=UITextBorderStyleRoundedRect;
    [self.view addSubview:_tf1];
    [self.view addSubview:_tf2];
    [self.view addSubview:_tf3];
   
    //进入后台,触发写文件方法,
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(write) name:UIApplicationDidEnterBackgroundNotification object:nil ];
    //进入应用时触发
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reade) name:UIApplicationDidBecomeActiveNotification object:nil ];
    
    NSDictionary* dic=[[NSDictionary alloc]initWithObjectsAndKeys:@"name",@"xxx",@"age",@"12",@"tel",@"13654846", nil];
    NSLog(@"%@",[dic objectForKey:@"12"]);
}
-(void)reade{
    //读取文件路径
    NSString * path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:@"writefile.text" ];
    NSLog(@"read path :%@",path);
    NSArray* arr=[NSArray arrayWithContentsOfFile:path];
    _tf1.text=arr[0];
    _tf2.text=arr[1];
    _tf3.text=arr[2];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    
}

-(void)write{
    NSString * path=[[NSBundle mainBundle]bundlePath];
    
    //path是文件夹,那么就再加上文件名才是文件完整路径
    NSString* path2=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    //    path2 = [path stringByAppendingString:@"/writefiles.tet"];
    path2= [path2 stringByAppendingPathComponent:@"writefile.text"];
    
    NSLog(@"%@,%@",path,path2);
    NSArray* writeArr=@[_tf1.text,_tf2.text,_tf3.text];
    
    [writeArr writeToFile:path2 atomically:YES];
    
}

//归档解决自定义对象
//数据持久化本质:保持状态跟数据

//归档调用,加密写入文件
-(void)loadView
{
    [super loadView];
   
    //从程序输入数据 并构建自定义对象(初始化要归档的对象,是数据的生成)
  
    Student* stu=[[Student alloc]initWithName:@"啊城" endAge:22 endTel:@"135321564"];
    //    NSArray* stu=[[NSArray alloc]initWithObjects:@"sss",@"aaaa",@"222", nil];
    NSMutableData* data=[[NSMutableData alloc]init];
    //构建归档器
    NSKeyedArchiver* archiver=[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    //归档 没有储存动作,只负责编码
    [archiver encodeObject:stu forKey:@"stu"];
    //千万不能忘记,归档完毕马上调用
    [archiver finishEncoding];
    
    //写入文档
    [data writeToFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:@"bba1.text" ] atomically:YES];
    NSLog(@"111 Stu name is %@,gender is %d,tel is %@",stu.name,stu.age,stu.tel);
}
//解档
-(void)encodeStu{
    //取数据,以待解码归档,注意一定要用NSDocumentDirectory
    NSData* data= [NSData dataWithContentsOfFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:@"bba1.text" ]];
    //解档器
    NSKeyedUnarchiver* uA=[[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    //解档->还原对象,注意解档和键需要和归档一致
    Student* stu=[uA decodeObjectForKey:@"stu"];
    //解码器,中decodeObjectForKay方法,在解码过程中,会调用initWithCoder方法,并通过对象类型到类中调用已重写实现的initWithCoder方法
    
    NSLog(@"2222  Stu name is %@,gender is %d,tel is %@",stu.name,stu.age,stu.tel);
    //
    [uA finishDecoding];
 
}


-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end

 

posted on 2015-12-16 10:23  摩羯小伟  阅读(154)  评论(0编辑  收藏  举报

导航