您的位置:首页 > 移动开发 > Objective-C

【Objective-C】OC中对象归档(序列化)的基本概念和用法

2014-02-13 09:44 411 查看
概念:归档是把对象写入文件保存在硬盘中,当再次重新打开程序时,可以还原这些对象。

数据持久化的方法:

1:NSKeyedArchiver-对象归档

2:NSUserDefaults

3:属性列表化(NSArray,NSDictonary保存文件)

4:SQlite数据库,CoreData数据库

归档的形式

1:对Foundation库中对象进行归档

2:自定义对象进行规定(需要实现归档协议,NSCoding)

3:归档后的文件是加密的,属性列表是明文的

实例

(一):使用数组为例,实现数组的归档和还原

     主要用到一下两个类:(NSKeyedArchiver与NSKeyedUnarchiver)的方法

     (1):+ (BOOL)archiveRootObject:(id)rootObject
toFile:(NSString *)path; //进行把对象归档到文件当中去

   (2):+ (id)unarchiveObjectWithFile:(NSString *)path;
  //根据文件的路径进行还原内容

     看下面代码:

#import <Foundation/Foundation.h>    
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
@autoreleasepool {
NSArray *array=@[@"abc",@"123",@5678];
NSString *homePath=NSHomeDirectory();
NSString *srcPath=[homePath stringByAppendingPathComponent:@"/Desktop/array.archiver"];
BOOL success=[NSKeyedArchiver archiveRootObject:array toFile:srcPath];
if (success) {
NSLog(@"归档成功.");
}
//进行还原
NSArray *resultArray= [NSKeyedUnarchiver unarchiveObjectWithFile:srcPath];
NSLog(@"%@",resultArray);
}
return 0;
}




自定义内容归档:

       归档:1:使用NSData实例作为归档的存储数据

               2:添加归档的内容(设置key与value) 

               3:完成归档,把归档的数据存入到硬盘中

       还原数据:

               1:从硬盘中读取文件,生成NSData实例

               2:根据Data实例进行创建和初始化还原归档文件实例

               3:还原文件,根据key去访问相应的value值

实例:使用自定义数据类型进行归档并且还原数据,看下实现代码:

      
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
@autoreleasepool {
//进行自定义对象写入归档
NSString *homePath=NSHomeDirectory();
NSString *srcPath=[homePath stringByAppendingPathComponent:@"/Desktop/custom.archiver"];
NSMutableData *data=[NSMutableData data];
NSKeyedArchiver *archiver=[[NSKeyedArchiver  alloc]initForWritingWithMutableData:data];
[archiver encodeInt:100 forKey:@"key1"];
NSArray *arrary=[NSArray arrayWithObjects:@"tom",@"jack", nil];
[archiver encodeObject:arrary forKey:@"key2"];
[archiver finishEncoding];
[archiver release];
BOOL success= [data writeToFile:srcPath atomically:YES];
if(success){
NSLog(@"写入成功...");
}

//进行还原数据
NSData *content=[NSData dataWithContentsOfFile:srcPath];
NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc ]initForReadingWithData:content];
NSUInteger result1= [unarchiver decodeIntForKey:@"key1"];
NSArray *result2=[unarchiver decodeObjectForKey:@"key2"];
NSLog(@"还原的数据为:");
NSLog(@"key1= %ld ",result1);
NSLog(@"key2= %@",result2);
}
return 0;
}


   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息