Nscoding 对类进行归档和反归档

NSCoding数据持久化的 方式之一。

数据持久化,实际上就是将数据存放到网络或者硬盘上,这里是存储到本地的硬盘上,应用程序的本地硬盘是沙盒,沙盒实际上就是一个文件夹,它下面有4个文件夹。分别是Documents,Library,APP包和tmp文件夹,Documents里面主要是存储用户长期使用的文件,Library里面又有Caches和Preferences文件夹,Caches里面存放的是临时的文件,缓存。Preferences里面存放的是偏好设置。tmp里面也是临时的文件,不过和Caches还有区别,APP包里面是编译后的一些文件,包不能修改。

NSCoding协议中只有两个方法,都是require的方法,一个是把本身的类进行转码,一个是逆转换成类对象,返回一个对象,我们实战一下这个协议的用法,看看是否好用,首先写一个自定义Student类:

@interfaceStudent : NSObject<NSCoding>

@property (nonatomic, retain) NSString *name;

@property (nonatomic, retain) NSString *ID;

-(Student *)initWithName :(NSString*)newName 

                 and : (NSString *)newID;

@end

Student类需要实现协议NSCoding,.m文件中是这样的:

@implementationStudent

@synthesize name = _name,ID = _ID;

//初始化学生类

-(Student *)initWithName:(NSString *)newName and:(NSString *)newID{

   self = [super init];

   if (self) {

       self.name = newName;

       self.ID= newID;

    }

   return self;

}

//学生类内部的两个属性变量分别转码

-(void)encodeWithCoder:(NSCoder *)aCoder{

   [aCoder encodeObject:self.name forKey:@"name"];

   [aCoder encodeObject:self.IDforKey:@"ID"];

}

//分别把两个属性变量根据关键字进行逆转码,最后返回一个Student类的对象

-(id)initWithCoder:(NSCoder *)aDecoder{

   if (self = [super init]) {

       self.name = [aDecoder decodeObjectForKey:@"name"];

       self.ID= [aDecoder decodeObjectForKey:@"ID"];

    }

   return self;

}

@end

自定义类Student实现了NSCoding协议以后,就可以进行归档转换了,具体实现:

   Student *stu1 = [[Student alloc]initWithName:@"124" and:@"111"];//学生对象stu1

   Student *stu2 = [[Student alloc]initWithName:@"223" and:@"222"];//学生对象stu2

   NSArray *stuArray =[NSArray arrayWithObjects:stu1,stu2, nil];//学生对象数组,里面包含stu1和stu2

   NSData *stuData = [NSKeyedArchiver archivedDataWithRootObject:stuArray];//归档

   NSLog(@"data = %@",stuData);

   NSArray *stuArray2 =[NSKeyedUnarchiver unarchiveObjectWithData:stuData];//逆归档

   NSLog(@"array2 = %@",stuArray2);

一个人,一片天,一条路,一瞬间!
原文地址:https://www.cnblogs.com/zcl410/p/4941899.html