iOS常用的存储方式介绍
在iOS App开发过程中经常需要操作一些需要持续性保留的数据,比如用户对于App的相关设置、需要在本地缓存的数据等等。本文针对OC中经常使用的一下存储方式做了个整理。
常用的存储工具/方式:
NSUserDefaults类
Plist文件
解归档
手动存放沙盒
// sqlite
CoreData
第三方数据存储框架
1. NSUserDefaults
一般对于一些基本的用户设置,因为数据量很小,我们可以使用OC语言中的 NSUserDefaults类来进行处理。使用方法很简单,只需要调用类中的方法即可:
NSMutableArray *mutArr = [[NSMutableArray alloc]initWithObjects:@"1", nil];
//存入数组并同步
[[NSUserDefaults standardUserDefaults] setObject:mutArr forKey:@"mutableArr"];
[[NSUserDefaults standardUserDefaults] synchronize];
//读取存入的数组 打印
NSArray *arr = [[NSUserDefaults standardUserDefaults] objectForKey:@"mutableArr"];
NSLog(@"%@",arr);
NSUserDefaults类除了可以存储数组、字典、NSdata外,还可以直接存储OC基本类型属性。但是不能直接作用到自定义对象,如果是自定义对象需要进行归档操作,这里后面会讲到。
2. Plist文件
Plist文件作为Xcode的一种资源包,也可以作为一种存储工具。
1.在项目中创建Plist文件。 在项目中创建的好处是文件的可视化,我们可以很直观的看到文件的内容,同时Xcode还提供了直接操作文件的功能。便于我们对文件内容的增删改查。这种方式的缺点是项目中的plist文件一般作为固态的数据形势保存,对于经常需要改动的数据就不好操作了。
获取文件中的数据代码
NSString *path = [[NSBundle mainBundle] pathForResource:@"Username" ofType:@"plist"];
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
NSLog(@"Username.plist内容%lu",(unsigned long)[data count]);
写入plist
2.代码读写Plist文件。避免了在项目中创建Plist文件导致不便更改的麻烦。
NSMutableDictionary *data=[[NSMutableDictionary alloc]init];
//添加数据
[data setObject:@"one" forKey:@"1"];
[data setObject:@"two" forKey:@"2"];
[data setObject:@"three" forKey:@"3"];
[data setObject:@"four" forKey:@"4"];
//要往沙盒中写数据当然要先取的沙盒目录啦
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *plistPaht=[paths objectAtIndex:0];
//取得完整的文件名
NSString *fileName=[plistPaht stringByAppendingPathComponent:@"Username.plist"];
NSLog(@"fileName is%@",fileName);
//创建并写入文件
[data writeToFile:fileName atomically:YES];
//检查是否写入
NSMutableDictionary *writeData=[[NSMutableDictionary alloc]initWithContentsOfFile:fileName];
NSLog(@"write data is :%@",writeData);
//读取plist
NSBundle *bundle=[NSBundle mainBundle];
//读取plist文件路径
NSString *path=[bundle pathForResource:@"citys" ofType:@"plist"];
//读取数据到 NsDictionary字典中
NSDictionary *dictionary=[[NSDictionary alloc]initWithContentsOfFile:path];
NSLog(@"size is %d",[dictionary count]);
//NSLog(@"data is %@",dictionary);
3.解归档
之前说了,不管是NSUserDefaults 或者是 plist 都不能对自定义的对象进行存储,OC提供了解归档恰好解决这个问题。 解归档针对的是一个对象,假设我们现在有一个TestModel的类,需要进行归档和接档,上代码。
对象的.h文件
#import <Foundation/Foundation.h>
@interface TestModel : NSObject <NSCoding> //解归档需要遵循Nscoding协议,并实现相关方法
@property (nonatomic,strong) NSString *name;
@property (nonatomic,assign) NSInteger age;
@property (nonatomic,strong) NSString *sex;
@end
对象的.m文件
#import "TestModel.h"
#define Name @"name"
#define Age @"age"
#define Sex @"sex"
@implementation TestModel
//需要实现NSCoding中的协议的两个方法
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self == [super init]) {
self.name = [aDecoder decodeObjectForKey:Name];
self.sex = [aDecoder decodeObjectForKey:Sex];
self.age = [[aDecoder decodeObjectForKey:Age] integerValue]; } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:self.name forKey:Name]; [aCoder encodeObject:self.sex forKey:Sex]; [aCoder encodeObject:[NSNumber numberWithInteger:self.age] forKey:Age]; } - (NSString *)description{ return [NSString stringWithFormat:@"%@--%@--%ld岁",self.name,self.sex,(long)self.age]; } @end
接下来只要使用解/归档辅助类就可以TestModel类进行解归档
//创建对象 并赋值
TestModel *model = [[TestModel alloc]init];
model.name = @"小明";
model.age = 25;
model.sex = @"man";
//归档
NSMutableData *data = [[NSMutableData alloc] init];
//创建归档辅助类
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; //编码 [archiver encodeObject:model forKey:@"model"]; //结束编码 [archiver finishEncoding]; //写入到沙盒 NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *fileName = [array.firstObject stringByAppendingPathComponent:@"archiverModel"]; if([data writeToFile:fileName atomically:YES]){ NSLog(@"归档成功"); } //解档 NSData *undata = [[NSData alloc] initWithContentsOfFile:fileName]; //解档辅助类 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:undata]; //解码并解档出model TestModel *unModel = [unarchiver decodeObjectForKey:@"model"]; NSLog(@"%@",unModel); //关闭解档 [unarchiver finishDecoding];
运行代码之后 打印
4.手动存放沙盒
iphone沙箱模型的有四个文件夹,分别是documents,tmp,app,Library。
1、Documents 目录:您应该将所有的应用程序数据文件写入到这个目录下。这个目录用于存储用户数据或其它应该定期备份的信息。为了不让App的备份过于庞大,我们不建议在这里存放大容量的文件。
2、AppName.app 目录:这是应用程序的程序包目录,包含应用程序的本身。由于应用程序必须经过签名,所以您在运行时不能对这个目录中的内容进行修改,否则可能会使应用程序无法启动。
3、Library 目录:这个目录下有两个子目录:Caches 和 Preferences
Preferences 目录:包含应用程序的偏好设置文件。您不应该直接创建偏好设置文件,而是应该使用NSUserDefaults类来取得和设置应用程序的偏好.
Caches 目录:用于存放应用程序专用的支持文件,保存应用程序再次启动过程中需要的信息。细心的话你会发现几乎所有的第三方框架的缓存信息处理都在这个文件中,一般的大容量文件都放在这里。
4、tmp 目录:这个目录用于存放临时文件,保存应用程序再次启动过程中不需要的信息。Nsuserdefaults保存的文件一般在tmp文件夹里。
获取这些目录路径的方法:
1,获取家目录路径的函数:
NSString *homeDir = NSHomeDirectory();
2,获取Documents目录路径的方法:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
3,获取Caches目录路径的方法:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
4,获取tmp目录路径的方法:
NSString *tmpDir = NSTemporaryDirectory();
沙盒中只能保存OC中的基本数据,自定义的对象不能直接存入。 存入方式如下。
// 1,获取家目录路径的函数:
// NSString *homeDir = NSHomeDirectory();
// 2,获取Documents目录路径的方法:
// NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// NSString *docDir = [paths objectAtIndex:0];
// 3,获取Caches目录路径的方法:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
// 4,获取tmp目录路径的方法:
// NSString *tmpDir = NSTemporaryDirectory();
//假设我们需往cache 存入数据,并命名为test的txt格式文件中
NSString *filePath = [cachesDir stringByAppendingPathComponent:@"test.txt"];
NSArray *dic = [[NSArray alloc] initWithObjects:@"test",@"test1" ,nil];
if([dic writeToFile:filePath atomically:YES]){
NSLog(@"存入成功"); } //取出数据 打印 NSLog(@"%@",[NSArray arrayWithContentsOfFile:filePath]);
打印如图: