iOS对象持久化归档 NSKeyedArchiver

来源:互联网 发布:看gv的软件 编辑:程序博客网 时间:2024/05/16 08:01
   之前我们有学习过用NSUserDefaults 来归档数据,可是

 NSUserDefaults是键值对的形势存在 只能存储包装好的整个数据,

 现在我们用NSKeyedArchiver 来存储对象。

  首先要在要存储的对象中修改NScoding协议和NScoping协议。

   

#import <Foundation/Foundation.h>


@interface Student :NSObject<NSCoding,NSCopying>

@property(nonatomic,retain)NSString *Name;

@property(nonatomic,retain)NSString *address;

@property(nonatomic,retain)NSString *gender;

@property(nonatomic,assign)int age;

   
在m文件中实现协议的修改


-(void)encodeWithCoder:(NSCoder *)aCoder

{

    //归档数据

    [aCoder encodeObject:_NameforKey:@"name"];//_Name 需要改为self.Name要不然回出现内存问题回奔溃的下面一样要改

    [aCoderencodeInt:_ageforKey:@"age"];

    [aCoder encodeObject:_genderforKey:@"gender"];

    [aCoder encodeObject:_addressforKey:@"address"];

}


//解码

-(id)initWithCoder:(NSCoder *)aDecoder

{

    if(self=[superinit])

    {

       _Name =[aDecoderdecodeObjectForKey:@"name"];

       _age =[aDecoderdecodeIntForKey:@"age"];

       _address=[aDecoderdecodeObjectForKey:@"address"];

       _gender=[aDecoderdecodeObjectForKey:@"gender"];

        

    }

            returnself;

}

//这个方法个人觉的 可以不用写, 一样可以实现

-(id)copyWithZone:(NSZone *)zone

{

   Student *stu=[[[selfclass]allocWithZone:zone]init];

    stu.Name=[self.NamecopyWithZone:zone];

    stu.address=[self.addresscopyWithZone:zone];

    stu.gender=[self.gendercopyWithZone:zone];

    stu.age=self.age;

   return stu;

}

 

到view界面去添加

-(NSString *)dataFilepath

{    //获取到document路径下的文件

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

   NSString *documentDier=[pathsobjectAtIndex:0];

    return [documentDierstringByAppendingPathComponent:@"code"];//后缀名 也可以不需要

}

- (void)viewDidLoad

{

    [superviewDidLoad];

   NSString *path=[selfdataFilepath];

    NSFileManager *file=[NSFileManagerdefaultManager];

   if([filefileExistsAtPath:path])

    {    //判断到有文件 开始解码

        NSMutableData *data=[[NSMutableDataalloc]initWithContentsOfFile:path];

        NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiveralloc]initForReadingWithData:data];

       Student *stu=[unarchiverdecodeObjectForKey:@"student"];

        [unarchiverfinishDecoding];

        

       self.name.text=stu.Name;

       self.age.text=[NSStringstringWithFormat:@"%d",stu.age];

       self.address.text=stu.address;

       self.gender.text=stu.gender;

        

        

        [datarelease];

        [unarchiverrelease];

    }

   //程序后台操作的时候程序发送消息通知, 受到通知后调用appear1:这个方法

    UIApplication *app=[UIApplicationsharedApplication];

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(appear1:)name:UIApplicationWillResignActiveNotificationobject:app];//object:app 表示必须是系统发送的通知

   

}

-(void)appear1:(NSNotification *)notification

{

    //把界面上text中的内容存到student类中

   Student *stu=[[Studentalloc]init];

    stu.Name=self.name.text;

    stu.age=[self.age.textintValue];

    stu.address=self.address.text;

    stu.gender=self.gender.text;

    // 归档student这个类

    NSMutableData *data=[[NSMutableDataalloc]init];

    NSKeyedArchiver *archiver=[[NSKeyedArchiveralloc]initForWritingWithMutableData:data];

    [archiverencodeObject:stuforKey:@"student"];

    [archiverfinishEncoding];

    

    [data writeToFile:[selfdataFilepath]atomically:YES];//gui dan lu jin 

    [datarelease];

    [archiverrelease];

    

    

}


- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


- (void)dealloc {

    [_namerelease];

    [_agerelease];

    [_genderrelease];

    [_addressrelease];

    [superdealloc];

}