iOS归档与解归档,持久化存储

点此下载iOS归档,持久化存储,解归档详细工程

//数据持久化的本质:将数据读取成文件保存在本地. 沙盒机制就是系统针对于每一个程序在本地生成的文件夹(名字随机生成), 对于不同的应用程序, 不能访问其他应用程序沙盒内的内容, 对于该应用程序内容起到保护作用:1 Documents:用来存储长久保存的数据 2 xxx.app:应用程序的包, 包含应用程序加载所需的所有资源(readonly只读, 不可修改), 平时使用的NSBundle就是该包 3 Library: 1) Caches:本地缓存, 存储想暂时保存的数据(Videos, Musics, Images) 比如:下载的视频, 音频, 图片都存储在该文件夹下 2) Preferences:存储用户的偏好设置, 比如程序是否是第一次启动 4 tmp:存储还未下载完的视频, 音频, 当下载完后, 将文件转移到Caches文件夹下

#import "WYLReadAndWriteViewController.h"
#import "WYLArchive.h"
@interface WYLReadAndWriteViewController ()<UITextFieldDelegate>

@end

@implementation WYLReadAndWriteViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"文件读写";
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(40, 84, 220, 40)];
    textField.tag = 100;
    textField.placeholder  = @"请输入内容";
    textField.delegate = self;
    textField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:textField];
    [textField release];
    UITextField *textField2 = [[UITextField alloc]initWithFrame:CGRectMake(40, 174, 220, 40)];
    textField2.tag = 101;
    textField2.placeholder  = @"显示上一个输入框的内容";
    textField2.delegate = self;
    textField2.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:textField2];
    [textField2 release];
    UIButton *writeButton = [UIButton buttonWithType:UIButtonTypeSystem];
     writeButton.frame =  CGRectMake(45, 260, 60, 30);
    [writeButton setTitle:@"写入" forState:UIControlStateNormal];
    [writeButton addTarget:self action:@selector(write:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:writeButton];
    UIButton *readButton = [UIButton buttonWithType:UIButtonTypeSystem];
    readButton.frame = CGRectMake(190, 260, 60, 30);
    [readButton setTitle:@"读取" forState:UIControlStateNormal];
    [readButton addTarget:self action:@selector(read:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:readButton];
    UIButton *push = [UIButton buttonWithType:UIButtonTypeSystem];
    push.frame = CGRectMake(120, 310, 60, 30);
    [push setTitle:@"push" forState:UIControlStateNormal];
    [push addTarget:self action:@selector(push:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:push];

}

- (NSString *)getFilePath
{
    //用来获取指定文件夹的路径:<#NSSearchPathDirectory directory#>:指定的文件夹;<#NSSearchPathDomainMask domainMask#>:设置查找的域, 我们自己的文件都是存储在永华域的;<#BOOL expandTilde#>:是否使用详细路径(绝对路径) 因为最初该方法是使用与MAC OS下的, 而对于电脑系统来说, 可能会存储多个用户, 所以获取到得用户可能有多个, 所以返回值类型是数组, 但是对于iOS下, 就要只有一个用户, 所以数组中只有一个元素
    /*
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //2)拼接上要存储文件的路径
    NSString *newFilePath = [documentsPath stringByAppendingPathComponent:@"aa.txt"];
    NSLog(@"%@", newFilePath);
     */
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *newPath = [filePath stringByAppendingPathComponent:@"test.txt"];
    NSLog(@"%@", newPath);
    return newPath;
}

- (void)read:(UIButton *)button
{
    //每次写入都会将之前的内容覆盖掉, 若想保留之前的数据, 需要讲之前的数据读出, 然后将要存储的数据拼接在一起, 一起存入
    /*
    NSString *newFilePath = [self getFilePath];
    NSError *error = nil;
    NSString *content = [NSString stringWithContentsOfFile:newFilePath encoding:NSUTF8StringEncoding error:&error];
    UITextField *tf = (UITextField *)[self.view viewWithTag:101];
    tf.text = content;
     */
    //字符串从本地读取
    /*
    NSString *filePath = [self getFilePath];
    NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    UITextField *tf = (UITextField *)[self.view viewWithTag:101];
    tf.text = content;
     */
    //数组从本地文件读取
    NSString *filePath = [self getFilePath];
//    NSArray *arr = [NSArray arrayWithContentsOfFile:filePath];
    //从字典从本地读取
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    UITextField *tf = (UITextField *)[self.view viewWithTag:100];
    UITextField *tf1 = (UITextField *)[self.view viewWithTag:101];
    tf.text = dic[@"tf2"];
    tf1.text = dic[@"tf1"];

}
//文件读写暂时只支持:NSString, NSArray, NSDictionary, NSData, 以及他们的子类.写入文件:writeToFile:(这是对象调用的方法), 读取文件:每一个类自带的能够根据路径创建对象的方法:[类名 类WithContentsOfFile]; 字符串:[NSString stringWithContentsOfFile], 数组:[NSArray arrayWithContentsOfFile], 字典:[NSDictionary dictionaryWithContentsOfFile], 二进制流:[NSData dataWithContentsOfFile],(牢牢谨记:对于数组, 字典这样的容器类, 内部的成员也必须是能够实现文件读写的八大类之一)
- (void)write:(UIButton *)button
{
    //写入时, 将第一个输入框中的文字, 写入到本地文件
    //1 获取存储的内容

    UITextField *tf = (UITextField *)[self.view viewWithTag:100];
    NSString *content = tf.text;
    //2 获取到所要存储的文件路径
    //1)获取Documents文件夹路径
    NSString *newFilePath = [self getFilePath];
    //3 将内容存储到指定文件路径
//    NSError *error = nil;
     //字符串写入本地文件
//    BOOL isSucceed = [content writeToFile:newFilePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
     //数组写入本地文件
    UITextField *tf2 = (UITextField *)[self.view viewWithTag:101];
    NSString *content1 = tf2.text;
//    NSArray *arr = @[content, content1];
//    BOOL isSucceed = [arr writeToFile:newFilePath atomically:YES];
    //字典写入本地文件
    NSDictionary *dic = @{@"tf1": content, @"tf2": content1};
    BOOL isSucceed = [dic writeToFile:newFilePath atomically:YES];
    NSLog(@"%d", isSucceed);

}
- (void)push:(UIButton *)button
{
    WYLArchive *archivieVC = [[WYLArchive alloc]init];
    [self.navigationController  pushViewController:archivieVC animated:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

#import "WYLArchive.h"
#import "Person.h"
@interface WYLArchive ()<UITextFieldDelegate>

@end

@implementation WYLArchive

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"归档与反归档";
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(40, 84, 220, 40)];
    textField.tag = 100;
    textField.placeholder  = @"请输入内容";
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.delegate = self;
    [self.view addSubview:textField];
    [textField release];
    UITextField *textField2 = [[UITextField alloc]initWithFrame:CGRectMake(40, 174, 220, 40)];
    textField2.tag = 101;
    textField2.placeholder  = @"显示上一个输入框的内容";
    textField2.borderStyle = UITextBorderStyleRoundedRect;
    textField2.delegate = self;
    [self.view addSubview:textField2];
    [textField2 release];
    UIButton *fileButton = [UIButton buttonWithType:UIButtonTypeSystem];
    fileButton.frame =  CGRectMake(45, 260, 60, 30);
    [fileButton setTitle:@"归档" forState:UIControlStateNormal];
    [fileButton addTarget:self action:@selector(file:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:fileButton];
    UIButton *archiveButton = [UIButton buttonWithType:UIButtonTypeSystem];
    archiveButton.frame = CGRectMake(190, 260, 60, 30);
    [archiveButton setTitle:@"反归档" forState:UIControlStateNormal];
    [archiveButton addTarget:self action:@selector(archive:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:archiveButton];

}

- (NSString *)getPath
{
    //获得文件夹的路径
    /*
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *newPath = [filePath stringByAppendingPathComponent:@"archive"];
    return newPath;
     */
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *newPath = [path stringByAppendingPathComponent:@"archiver"];
    return newPath;
}
- (void)file:(UIButton *)button
{
    //获取输入框的内容
    UITextField *tf1 = (UITextField *)[self.view viewWithTag:100];
    UITextField *tf2 = (UITextField *)[self.view viewWithTag:101];
    /*
    //封装成Person对象
    Person *person = [[Person alloc] initWithName:tf1.text gender:tf2.text age:18];
    //1 创建归档对象
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    //2 归档
    [archiver encodeObject:person forKey:@"person"];
    [person release];
    //3 结束归档, 当结束归档之后, 再归档无效
    [archiver finishEncoding];
    [archiver release];
    //4 data写入文件
    [data writeToFile:[self getPath] atomically:YES];
     */
    Person *person = [[Person alloc] initWithName:tf1.text gender:tf2.text age:18];
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:person forKey:@"archiver"];
    [person release];
    [archiver finishEncoding];
    [archiver release];
    [data writeToFile:[self getPath] atomically:YES];
}
- (void)archive:(UIButton *)button
{
    /*
    //1 初始化NSMutableData对象
    NSMutableData *data = [NSMutableData dataWithContentsOfFile:[self getPath]];
    //2 创建一个反归档对象
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    //3 反归档
    Person *person = [unarchiver decodeObjectForKey:@"person"];
    //4 结束反归档
    [unarchiver finishDecoding];
    [unarchiver release];
     */
    NSMutableData *data = [NSMutableData dataWithContentsOfFile:[self getPath]];
    NSKeyedUnarchiver *unarchive = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    Person *person = [unarchive decodeObjectForKey:@"archiver"];
    [unarchive finishDecoding];
    [unarchive release];
    UITextField *tf1 = (UITextField *)[self.view viewWithTag:100];
    UITextField *tf2 = (UITextField *)[self.view viewWithTag:101];
    tf1.text = person.gender;
    tf2.text = person.name;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

时间: 2024-10-05 19:56:21

iOS归档与解归档,持久化存储的相关文章

iOS:沙盒、偏好设置、归档、解归档

一.沙盒和应用程序包 •iOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被称为沙盒 •iOS常用目录: –Bundle –Documents –Library/Caches –Library/Preference –tmp 显示mac隐藏文件:defaults write com.apple.finder AppleShowAllFiles -bool true 隐藏mac隐藏文件:defaults write com.apple.finder AppleSh

IOS阶段学习第18天笔记(归档与解归档操作)

IOS学习(OC语言)知识点整理 一.归档与解归档的操作 1)归档是一个过程,将一个或多个对象存储起来,以便以后可以还原,包括将对象存入文件,以后再读取 将数据对象归档成plist文件 2)plist文件中只能存放:NSString.NSDate.NSNumber.Bool.NSData.NSArray.NSDictionary 并且NSArray和NSDictionary中只能是以上的类型 3)归档存放时数据是什么类型,读取数据时就用什么类型的数据接收. 4)归档不能直接操作自定义对象类型的数

关于iOS开发归档与解归档路径问题

今天回头看了一下归档与解归档,有普通的归档与解归档,更好的方法是runtimer.在这里我不是讲归档与解归档,而是讲很多文档中出现的一个问题,希望给大家带来帮助,不说废话了,上代码. 1:错误的代码 NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"person"]; 很多文章中用这样的方式获取路径,这句代码的的意思是,在主路径上拼接一个person路径.可惜不成功,不成功的原因应该是苹果手机权限问题.

OC-多个自定义对象的归档与解归档

对于上一章节,简单讲述了一个自定义对象的归档与解归档:http://www.cnblogs.com/BeyondAverage0908/p/4597245.html 本章节阐述下多个自定义对象的归档与解归档 以下代码阐述:定义了两个类Dog和Cat,并且利用@property展开了对应的几个属性(简单的代码,不贴源码了). 以下代码部分位主要的归档与解归档代码:注意需要在对应的自定义类中实现以下两个方法:- (void)encodeWithCoder:(NSCoder *)aCoder;方法,-

OC-自定义对象的归档与解归档

对于系统对象进行归档与接归档直接使用类提供的方法 参考:http://www.cnblogs.com/BeyondAverage0908/p/4596798.html 但是对于自定义的对象,当使用系统的类方法进行归档和解归档时,就会出现内存错误,错误信息是没有实现(归档时)- (void)encodeWithCoder:(NSCoder *)aCoder;方法,(解归档)时没有实现:- (id)initWithCoder:(NSCoder *)aDecoder; 所以如果需要自定义对象的归档与解

【OC学习-27】对象的归档以及解归档——标准数据和自定义数据的例子

对象归档?就是把对象的数据保存成文件实现数据的加密(即在文档中不是明文显示)和永久储存. 需要使用时,则从文件中恢复即可. (1)标准的数据 //main.m文件 #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { //把一个数组进行归档 //创建一个文件路径 NSString *homePath=NSHomeDirectory(); NSString *f

持久化存储---归档一

一.流程图 二.代码 1.模型归档 (1) @interface Person : NSObject<NSCoding>//归档调用的方法 - (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeInteger:self.age forKey:@"age"]; [aCoder encodeObject:

归档类与解归档类的属性以及方法的了解

归档的方式就是将数据通过密文的方式存储,或者说是可以通过二进制进行存储. 归档的属性和方法:NSKeyedArchiver  FOUNDATION_EXPORT NSString * const NSInvalidArchiveOperationException; FOUNDATION_EXPORT NSString * const NSInvalidUnarchiveOperationException; 上面的两个常量都是用来处理异常的,一个是归档一个是解压归档的时候使用的.s FOUND

iOS开发简单高效的数据存储

学习交流讨论请关注新浪微博:极客James 在iOS开发过程中,不管是做什么应用,都会碰到数据保存的问题,你是用什么方法来持久保存数据的?这是在几乎每一次关于iOS技术的交流或讨论都会被提到的问题,而且大家对这个问题的热情持续高涨.本文主要从概念上把"数据存储"这个问题进行剖析,并且结合各自特点和适用场景进行全面抛析.. 一.NSUserDefaults NSUserDefaults被设计用来存储设备和应用的配置信息,它通过一个工厂方法返回默认的.也是最常用到的实例对象.这个对象中储存