zoukankan      html  css  js  c++  java
  • objective C中数据持久化方式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!");
            
        }
    


  • 相关阅读:
    NTP on FreeBSD 12.1
    Set proxy server on FreeBSD 12.1
    win32 disk imager使用后u盘容量恢复
    How to install Google Chrome Browser on Kali Linux
    Set NTP Service and timezone on Kali Linux
    Set static IP address and DNS on FreeBSD
    github博客标题显示不了可能是标题包含 特殊符号比如 : (冒号)
    server certificate verification failed. CAfile: none CRLfile: none
    删除文件和目录(彻底的)
    如何在Curl中使用Socks5代理
  • 原文地址:https://www.cnblogs.com/james1207/p/3358202.html
Copyright © 2011-2022 走看看