iOS开发数据持久化,归档方法

1.把要显示的数据转换为模型,把对象归档,然后把存起来的对象解析出来就可以使用

2.可以封装起来方便使用,封装的方法存入百度云,需要的可以留言

 

/** 归档方法 */
-(void)archive
{
    /**
     *     常用的几个文件目录   directory目录
     * NSDownloadsDirectory 下载文件目录
     * NSDocumentDirectory 数据文件目录
     * NSCachesDirectory 缓存文件目录
     * NSMoviesDirectory 电影文件目录
     * NSPicturesDirectory 图片文件目录
     * NSMusicDirectory 音乐文件目录
     *
     */
    NSArray *myPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //Document目录下的第一个文件对象
    NSString *docPath = [myPaths firstObject];
    //新建一个文件并返回该文件路径
    NSString *fileNamePath = [docPath stringByAppendingPathComponent:@"archive.data"];
    //归档
    [NSKeyedArchiver archiveRootObject:@"数据模型" toFile:fileNamePath];
    //读档
    NSString *duixaing = [NSKeyedUnarchiver unarchiveObjectWithFile:fileNamePath];

    
}

存档的另一种方法,自己需要研究的是归档的路径,归档的方法 ,读档的方法(注明用的是两个不同的类,一个是存档的类,一个是读档的类,)

存的数据是以二进制的形式存进手机本地的

/** 保存数据进行归档 */
- (IBAction)saveBtn:(id)sender {
    NSString *filePath = [self filePathWithfileName:@"student.archive"];
    NSMutableData *theData = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:theData];
    studentsInfo *Info = [[studentsInfo alloc] init];
    Info.sno = self.snoLabel.text;
    Info.name = self.nameLabel.text;
    Info.classes = self.classLabel.text;
    [archiver encodeObject:Info forKey:@"mystudent"];
    [archiver finishEncoding];
    [theData writeToFile:filePath atomically:YES];
    NSLog(@"%@",filePath);
}
/** 归档文件读取数据 */
- (IBAction)readBtn:(id)sender {
    NSString *filePath = [self filePathWithfileName:@"student.archive"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    if (data.length > 0) {
        NSKeyedUnarchiver *Unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        studentsInfo *Info = [Unarchiver decodeObjectForKey:@"mystudent"];
        [Unarchiver finishDecoding];
        self.snoLabel.text = Info.sno;
        self.nameLabel.text = Info.name;
        self.classLabel.text = Info.classes;
    }
    
}

/** 返回一个在document文件下的文件的路径(自己创建的文件) */
-(NSString *)filePathWithfileName:(NSString *)fileName
{
    NSArray *myPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *myDocPath = [myPaths firstObject];
    
    NSString *filename = [myDocPath stringByAppendingPathComponent:fileName];
    return filename;
}

 


如图示封装的伪代码,使用方法引用头儿文件既可。

转载于:https://www.cnblogs.com/ZHP-Study-share/p/5419202.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值