设为首页 加入收藏

TOP

objective C中数据持久化方式1--对象归档
2014-11-23 21:53:55 来源: 作者: 【 】 浏览:9
Tags:objective 数据 持久化 方式 1-- 对象 归档
第一、数据持久化的方式:
NSKeyedArchiver--对象归档
属性列表化(NSArray、NSDictionary、NSUserDefault)
SQlite 数据库、CoreData数据库
其中第一、二种方式针对数据量小的数据,第三种方式针对大数据,归档的文件是 加密的,属性列表明文的。
归档的形式;
对foundation库中对象进行归档
自定义对象的归档(需要实现归档协议:NSCoding)
第二 最简单归档和解归档的实现代码:
@autoreleasepool {  
    NSString *homeDictory=NSHomeDirectory();  
    NSArray *array=[NSArray arrayWithObjects:@"one",@"two",@"three",nil];  
    NSString *homePath=[homeDictory stringByAppendingPathComponent:@"Desktop/test.archive"];  
    if(![NSKeyedArchiver archiveRootObject:array toFile:homePath])  
    {  
        NSLog(@"归档失败");  
    }else  
    {  
        NSArray *data=[NSKeyedUnarchiver unarchiveObjectWithFile:homePath];  
        NSLog(@"%@",data);  
      
    }  
      
    NSLog(@"Hello, World!");  
      
}  

第四、复杂的内容归档
使用NSData实例作为归档的存储数据,添加归档的内容(设置key和value),完成归档,将归档内容存入磁盘
解归档步骤:从磁盘读取文件,生成NSData实例,根据data实例创建或初始化归档实例,解归档,根据key访问value的值
NSString *homeDictory=NSHomeDirectory();  
NSString *homePath=[homeDictory stringByAppendingPathComponent:@"Desktop/usertest.archive"];  
  
NSMutableData *data=[NSMutableData data];  
NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc] initForWritingWithMutableData:data];  
  
NSArray *nameArray=[NSArray arrayWithObjects:@"andy",@"yang", nil];  
[archiver encodeInt:100 forKey:@"age"];  
[archiver encodeObject:nameArray forKey:@"names"];  
[archiver finishEncoding];  
[archiver release];  
  
if ([data writeToFile:homePath atomically:YES])  
{  
  
    NSData *data2=[NSData dataWithContentsOfFile:homePath];  
    NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data2];  
    int age=[unarchiver decodeIntForKey:@"age"];  
    NSArray *array2=[unarchiver decodeObjectForKey:@"names"];  
    NSLog(@"%d",age);  
    NSLog(@"%@",array2);  
    [unarchiver release];  
} else  
{  
      
    NSLog(@"write to file wrong");  
}  
          
NSLog(@"Hello, World!");  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇objective-C 自定义对象归档的实现 下一篇由链表初始化看C语言的二级指针

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: