码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2016-04-21 23:18:59      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

 


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

技术分享技术分享

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

标签:

原文地址:http://www.cnblogs.com/ZHP-Study-share/p/5419202.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!