数据持久化

1.数据持久化(存储数据)的方式:

①.plist文件

②.NSUserDefault(存放当前的配置信息或者程序的状态信息,存储的信息量比较少)

③.sqlite(轻量级数据库,属于关系型数据库,不能直接存储对象,需要使用一些sql语句,将对象归档成简单对象存储).

④.CoreData(对象型数据库,把数据库的内部存储细节给封装了).

⑤writeToFile:

2.应用程序的沙盒

每个ios应用程序都有自己的应用沙盒(文件系统目录)与其他的应用程序沙盒是隔离的,应用程序本身只能呆在自己的沙盒里和访问自己的沙盒内的数据.其他应用程序是不能访问该沙盒的(ios8以后,在一定程度上开放了访问).

3.应用程序沙盒(文件系统结构)分析:

.App(应用程序包):包含了程序自带的所有资源文件(如:图片,音频等)和可执行文件.

Documents:保存应用程序运行时生成的需要持久化的数据.iTunes同步移动设备上的数据时,会(在documents下)备份该目录.

tmp:保存应用程序运行时所需要的临时数据,使用完毕后,系统会将相应的文件,从该目录中移除.iTunes同步设备上的数据时,不会备份该目录.

library:/Caches:保存应用程序运行时产生的需要持久化的数据.一般存储数据量比较大或者不是太重要的数据

library/Preference:保存应用程序的所有设置.包括>iOS setting(设置),程序在运行的时候会在该目录中查找这个应用程序有没有相关的设置文件,如果有就读取.

 

#import "ViewController.h"

#import "Person.h"

@interface ViewController ()

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    //1.获取应用程序沙盒中的Decument文件夹路径

    //第一种方式:

   NSString *documentPath= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;

    //新建的沙盒文件是放在最后的,所以通过lastObject可以获取到

    NSLog(@"%@",documentPath);

   //第二种方式;

    //获取你的应用程序的沙盒文件夹

    NSString *homePath=NSHomeDirectory();

    NSLog(@"%@",homePath);

  NSString *documentsPath1=[homePath stringByAppendingPathComponent:@"Document"];

    NSLog(@"%@",documentsPath1);

    //查看应用程序包xxx.app

    NSLog(@".appPath=%@",[NSBundle mainBundle].resourcePath);

    

  //获取Caches路径

//    NSString *cachesPath=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;

//    NSLog(@"%@",cachesPath);

 

#pragma mark-------------------简单对象写入文件

    //一,向一个文件中写入字符串

    NSString *string=@"I love you very much!";

    //1.拼接文件路径

 NSString *filePath=[documentPath stringByAppendingPathComponent:@"note.txt"];

    //2.将字符串写入文件

    [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@",filePath);

  //3.读取文件中的字符串

  NSString *str=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@",str);

  //二,向一个文件中写入数组

    //1.拼接文件存储的路径

   NSString *arrayPath= [documentPath stringByAppendingPathComponent:@"array.txt"];

    //数据

    NSArray *array=[NSArray arrayWithObjects:@"尹线",@"郭超",@"喻沛东", nil];

    //2.将数组写入文件

    [array writeToFile:arrayPath atomically:YES];

    NSLog(@"%@",arrayPath);

    //3.从文件中读取数组

    NSArray * array1=[NSArray arrayWithContentsOfFile:arrayPath];

    NSLog(@"%@",array1);

  //三,向一个文件中写入字典

    //1.拼接文件存储的路径

    NSString *dicPath=[documentPath stringByAppendingPathComponent:@"dictionary.txt"];

    //数据

    NSDictionary *dic=[NSDictionary dictionaryWithObject:@"xiaoxiao" forKey:@"name"];

    //NSDictionary *dic=[NSDictionary dictionaryWithObjects:@"张三",@"男",@"19" forKeys:@"name",@"sex",@"age"];

    //2.将字典写入文件中

    [dic writeToFile:dicPath atomically:YES];

    NSLog(@"%@",dicPath);

    //3.从文件中读取字典

    NSDictionary *dict=[NSDictionary dictionaryWithContentsOfFile:dicPath];

    NSLog(@"%@",dict);

  //四,向文件里存入NSData类型数据

    UIImage *image=[UIImage imageNamed:@"0.jpg"];

    NSData *data=UIImageJPEGRepresentation(image, 1);

    //2.写入文件

    NSString *dataPath=[documentPath stringByAppendingPathComponent:@"data.txt"];

    [data writeToFile:@"data" atomically:YES];

    NSLog(@"%@",dataPath);

    //

    NSData *data1=[NSData dataWithContentsOfFile:dataPath];

    NSLog(@"%@",data1);

    UIImage *image1=[UIImage imageWithData:data1];

    NSLog(@"%@",image1);

    

#pragma mark----------NSFileManger管理文件类

    //1.创建文件夹

    //拼接路径(表示在那个文件夹下面创建的文件夹,文件夹的名字是什么)

  NSString *path1=[documentPath stringByAppendingPathComponent:@"path1"];

    //创建文件夹

    NSDictionary *dic2=@{@"creatTime":@"2015-5.8"};

    [[NSFileManager defaultManager]createDirectoryAtPath:path1 withIntermediateDirectories:YES attributes:dic2 error:nil];

    //在自己创建的文件夹下写入一个文件

    NSString *path2=[path1 stringByAppendingPathComponent:@"like.txt"];

    [[NSFileManager defaultManager]createFileAtPath:path2 contents:data attributes:nil];

    NSLog(@"%@",path2);

#pragma mark-------------library/Caches/path/image.txt

  //获取library Caches

    NSString *cachesPath=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;

    NSLog(@"%@",cachesPath);

    //拼接路径

   NSString *path3= [cachesPath stringByAppendingPathComponent:@"path"];

    //创建path文件夹

    [[NSFileManager defaultManager]createDirectoryAtPath:path3 withIntermediateDirectories:YES attributes:nil error:nil];

    //拼接文件路径

    NSString *cachesPath2=[path3 stringByAppendingPathComponent:@"image.txt"];

    //创建文件

    [[NSFileManager defaultManager]createFileAtPath:cachesPath2 contents:nil attributes:nil];

    NSLog(@"%@",cachesPath2);

 //删除文件

    //①.判断需要删除的文件存不存在

  BOOL flag=  [[NSFileManager defaultManager]fileExistsAtPath:cachesPath2];

    NSLog(@"%d",flag);

  //如果文件存在删除它

    if (flag) {

        [[NSFileManager defaultManager] removeItemAtPath:cachesPath2 error:nil];

    }

  

#pragma mark------------对复杂对象进行数据持久化

#pragma mark-----将复杂对象存入文件-------(顺序:复杂对象->归档->NSData->拼接文件路径->writeToFile)

    Person *person=[[Person alloc] init];

    person.name=@"张三";

    person.age=@"20";

    person.sex=@"男";

    //创建一个可变的NSMutableData对象,用来存放person对象被归档之后的data数据的.

    NSMutableData *personData=[NSMutableData data];

    //创建一个归档工具对象

    NSKeyedArchiver *archiver=[[NSKeyedArchiver alloc] initForWritingWithMutableData:(personData)];

    //开始对person对象进行归档(person->NSData)

    [archiver encodeObject:person forKey:@"person"];

    //注意:当归档结束时,一定要调用finishEncoding

    [archiver finishEncoding];

    //完成转换了(person->NSData的转换),此时personData里存放的就是person对象被归档之后的NSData类型数据

    //拼接存放数据的文件路径

    NSString *personCachesPath=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject ;

   NSString *personPath1=[personCachesPath stringByAppendingPathComponent:@"person.txt"];

    //将归档之后的personData数据写入person.txt中

    [personData writeToFile:personPath1 atomically:YES];

    

    NSLog(@"***********%@",personPath1);

#pragma mark-----从文件中读取复杂对象-------(顺序:获取文件路径->读取NSData数据->反归档->得到复杂对象)

  NSData *data3=[NSData dataWithContentsOfFile:personPath1];

    //创建一个反归档工具对象

    NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc] initForReadingWithData:data3];

    //开始对NSdata类型数据进行反归档(将NSData类型数据转换为复杂对象)

  Person *person1=[unarchiver decodeObjectForKey:@"person"];

    [unarchiver finishDecoding];

    NSLog(@"#########%@",person1);

    NSLog(@"name=%@",person1.name);

    NSLog(@"age=%@",person1.age);

    NSLog(@"sex=%@",person1.sex);

    

}

 

Person.h

 

@interface Person : NSObject<NSCoding>

@property(nonatomic,retain)NSString *name;

@property(nonatomic,retain)NSString *sex;

@property(nonatomic,retain)NSString *age;

 

Person.m

 

-(void)dealloc{

    [_name release];

    [_sex release];

    [_age release];

    [super dealloc];

 

}

 

#pragma mark-------------对类中的所有属性进行编码

-(void)encodeWithCoder:(NSCoder *)aCoder{

 

    [aCoder encodeObject:self.name forKey:@"name"];

    [aCoder encodeObject:self.age forKey:@"age"];

    [aCoder encodeObject:self.sex forKey:@"sex"];

}

#pragma mark------------对类中的所有方法进行反编码

 

-(id)initWithCoder:(NSCoder *)aDecoder{

    self=[super init];

    if (self) {

       self.name=[aDecoder decodeObjectForKey:@"name"];

        self.age=[aDecoder decodeObjectForKey:@"age"];

        self.sex=[aDecoder decodeObjectForKey:@"sex"];

    }

    return self;

}

 

下面的摘自:http://blog.sina.com.cn/s/blog_a843a8850101drnz.html

NSUserDefaults用于存储数据量小的数据,例如用户配置。并不是所有的东西都能往里放的,只支持:NSString,NSNumber, NSDate, NSArray, NSDictionary,详细方法可以查看类文件。

 NSUserDefaultsstandardUserDefaults用来记录一下永久保留的数据非常方便,不需要读写文件,而是保留到一个NSDictionary字典里,由系统保存到文件里,系统会保存到该应用下的/Library/Preferences/gongcheng.plist文件中。需要注意的是如果程序意外退出,NSUserDefaultsstandardUserDefaults数据不会被系统写入到该文件,不过可以使用[[NSUserDefaultsstandardUserDefaults] synchronize]命令直接同步到文件里,来避免数据的丢失。

一、将数据存储到NSUserDefaults:

//UISwitch

- (IBAction)switchChanged:(id)sender{

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

        [userDefaults setBool:_theSwitch.on forKey:@"switchValue"];

}

 

//UITextField

- (IBAction)inputChanged:(id)sender{

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

        [userDefaults setObject:_textField.text forKey:@"inputValue"];

}

 

二、读取NSUserDefaults中的数据:

//UISwitchNSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];BOOL sw = [userDefaults boolForKey:@"switchValue"];[_theSwitch setOn:sw];//UITextFieldNSString *str = [userDefaults stringForKey:@"inputValue"];[_textField setText:str];
registerDefaults:方法是注册偏好设置的子集,它是不写入到plist文件中的,但在ND中取确实能取到。
也就是说plist文件中看到的数据是你显示的设置进去的。
比如调用setxxx方法

posted @ 2015-06-25 10:02  脉脉不得语  阅读(238)  评论(0编辑  收藏  举报