iOS 数据持久化-归档

来源:互联网 发布:巴西黑帮知乎 编辑:程序博客网 时间:2024/05/18 04:30

1.将任何对象,或数据结构转换为NSData类对象的过程,成为归档,亦称之为数据的序列化


2.解归档,首先要确保你有同样的数据结构来接收解归档的数据

 


需要归档的数据结构中,任何对象都必须遵从NSCoding,实现协议方法

- (void)encodeWithCoder:(NSCoder*)aCoder; // 归档时调用,

 

- (id)initWithCoder:(NSCoder *)aDecoder; //解归档时调用


使用KeyedAchiever进行归档,使用KeyedUnAchiever进行解归档

注:多层数据结构嵌套是时归档要进行深拷贝,即,如果要归档的对象中有子对象,子对象应该继续归档,以下为例:

WWCClass类中有一个WWCStudent对象,存储在WWCClass类中的一个数组中,对WWCClass类归档时如下结构

类WWCClass类Student:


@implementation WWCClass

- (void)encodeWithCoder:(NSCoder *)aCoder

{

   [aCoder encodeObject:_array forKey:@"array"];

}


- (id)initWithCoder:(NSCoder *)aDecoder

{

    if (self =[super init]){

       //从数据结构中取出数据,长时间使用,需要retain

      //解归档过程中还原的数据都要retaincopy

       _array =[[aDecoder decodeObjectForKey:@"array"retain];

    }

   return self;

 

}


类WWCStudent:

@interfaceWWCStudent : NSObject


@property (copy)NSString*name;

@property (copy)NSString*ID;

@propertyNSUInteger age;


@end


@implement WWCStudent

- (void)encodeWithCoder:(NSCoder*)aCoder

{

    //当学生被归档,会委托调用这个方法

    //在这个方法里,归档学生的属性

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

    //归档时需要设置一个key,方便解归档时查找数据。

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

//    [aCoderencodeObject:@(self.age) forKey:@"age"];

   [aCoder encodeInteger:self.ageforKey:@"age"];

}


- (id)initWithCoder:(NSCoder*)aDecoder

{

   //解归档时调用

    if(self= [superinit]){

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

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

       self.age= [aDecoder decodeIntegerForKey:@"age"];

    }

   return self;

}

main 函数 

归档:

WWCClas*student = [[WWCClasalloc]init];

[student addStudent];// 此函数是为student添加数据

       

NSMutableData *data= [[NSMutableData alloc]init];

NSKeyedArchiver *achiver= [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];

       

[achiver encodeObject:studentforKey:@"student"];

[achiver finishEncoding];

 

[datawriteToFile:PATHatomically:YES];

解归档

NSData *data= [NSData dataWithContentsOfFile:PATH];

       

NSKeyedUnarchiver *unchiver= [[NSKeyedUnarchiver alloc]initForReadingWithData:data];

WWCClas* student = [[unchiver decodeObjectForKey:@"student"]retain];

[unchiver finishDecoding];


0 0