本文由我们团队的王瑞华童鞋撰写。
数据持久化就是将内存中的数据模型转换为存储模型,以及将存储模型转换为内存中的数据模型的统称。 数据模型可以是任何数据结构或对象模型,存储模型可以是关系模型、XML、二进制流等。在iOS开发中,有很多种数据持久化方案,本文主要介绍 plist文件,NSKeyedArchiver,SQLite3,NSUserDefaults。
iOS的沙盒模型
iOS最为人所熟知的就是其沙盒模型,一个App的读写权限只限于自己的沙盒目录中。沙盒模型的好处有哪些?1. 安全,别的app无法修改你的程序。2. 保护隐私,别人app无法读取你的程序。3.便于系统管理,一个app产生的内容都包含在自己的沙盒中,便于系统管理。
iOS 沙盒目录结构如下
1
2
3
4
5
6
|
App
Bundle
,
如
xxx
.
app
其实是一个目录,里面包含
app二进制数据以及资源文件
Documents
,
存放程序产生的文档数据
Library
Caches
Preferences
tmp
,临时文件目录,目前我所知道的是下载文件会在此文件暂存,完成后进行处理
|
如果我们想获取上面某个目录的路径,应该如何实现呢?
对于最常用的Documents目录,iTunes同步该应用时会同步该文件夹内容,适合存放用户重要数据
1
2
|
NSString
*searchPath
=
[
NSSearchPathForDirectoriesInDomains
(
NSDocumentDirectory
,
NSUserDomainMask
,
YES
)
lastObject
]
;
NSLog
(
@"%@"
,
searchPath
)
;
|
Library/Caches:iTunes不会同步该文件夹
Library/Preferences: iTunes同步该应用时会同步此文件夹中的内容,通常保存应用的设置信息。
1
2
|
NSString
*path
=
[
NSSearchPathForDirectoriesInDomains
(
NSCachesDirectory
,
NSUserDomainMask
,
YES
)
firstObject
]
;
NSLog
(
@"%@"
,
path
)
;
|
tmp:此目录适合保存应用中的一些临时文件,用完就删除。
1
2
|
NSString
*path
=
NSTemporaryDirectory
(
)
;
NSLog
(
@"%@"
,
path
)
;
|
NSFileManager
在实际项目开发中,我们一般会创建一个工具类来对app的文件进行管理。
NSFileManager 提供一个类方法获得一个单例。
1
|
+
(
NSFileManager
*
)
defaultManager
|
下面是NSFileManager的常用方法
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/*新建目录,createIntermediates这个参数一般为YES,
*表示如果目录路径中间的某个目录不存在则创建之,
*如果是NO的话,则要保证所创建目录的父目录都必须已经存在
*/
-
(
BOOL
)
createDirectoryAtPath
:
(
NSString
*
)
path
withIntermediateDirectories
:
(
BOOL
)
createIntermediates
attributes
:
(
NSDictionary
*
)
attributes
error
:
(
NSError
*
*
)
error
;
// 获取目录下的所有文件
-
(
NSArray
*
)
contentsOfDirectoryAtPath
:
(
NSString
*
)
path
error
:
(
NSError
*
*
)
error
;
-
(
BOOL
)
copyItemAtPath
:
(
NSString
*
)
srcPath
toPath
:
(
NSString
*
)
dstPath
error
:
(
NSError
*
*
)
error
;
-
(
BOOL
)
moveItemAtPath
:
(
NSString
*
)
srcPath
toPath
:
(
NSString
*
)
dstPath
error
:
(
NSError
*
*
)
error
;
-
(
BOOL
)
linkItemAtPath
:
(
NSString
*
)
srcPath
toPath
:
(
NSString
*
)
dstPath
error
:
(
NSError
*
*
)
error
;
-
(
BOOL
)
removeItemAtPath
:
(
NSString
*
)
path
error
:
(
NSError
*
*
)
error
;
|
plist 文件
plist文件的实质为XML文件,很容易查看到文件数据类型。可以被plist文件序列话的类型只有以下几种:
- NSArray, NSMutableArray
- NSDictionary, NSMutableDictionary
- NSData, NSMutableData
- NSString, NSMutableString
- NSNumber
- NSDate
而在实际的项目中,我们一般是将NSDictionary或NSArray的对象保存到文件或者从文件读取成对象。NSDictionary和NSArray会直接写成plist文件。
1
|
-
(
BOOL
)
writeToFile
:
(
NSString
*
)
path
atomically
:
(
BOOL
)
useAuxiliaryFile
;
|
序列化可以通过两种途径来进行
- 使用数据对象自带方法
123456789// 文件的写入NSString *path = NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory , NSUserDomainMask , YES ) . firstObject ;NSString *fileName = [ path stringByAppendingPathComponent : @"test.plist" ] ;NSDictionary *dict = @ { @"one" : @ 1 ,@"two" : @ 2 } ;[ dict writeToFile :fileName atomically :YES ] ;// 文件的读取NSDictionary *dictFF = [ NSDictionary dictionaryWithContentsOfFile :fileName ] ; - 使用NSPropertyListSerialization类
12345678910111213141516171819202122NSDictionary *dict = @ { @"one" : @ 1 ,@"two" : @ 2 } ;NSString *error ;NSData *xmlData = [ NSPropertyListSerialization dataFromPropertyList :dataDictionaryformat :NSPropertyListXMLFormat_v1_0errorDescription : & error ] ;if ( xmlData ) {NSLog ( @"No error creating XML data." ) ;[ xmlData writeToFile :fileName atomically :YES ] ;}else {if ( error ) {NSLog ( @"error:%@" , error ) ;}}// 读取NSDictionary *dictFF = ( NSDictionary * ) [ NSPropertyListSerializationpropertyListWithData : [ NSData dataWithContentsOfFile :fileName ]options : 0format :NULLerror : & error ] ;
UserDefault
顾名思义,它就是一个用户的一些偏好设置。对于该部分,每一个app都要一个plist文件专门保存偏好设置数据。 plist文件名默认是程序Bundle identifier,扩展名为plist。除了程序自己的设置外,系统还有一些全局的或者其它的一些设置,也属于User Defaults的范畴,User Defaults的持久化数据都保存在 ~/Library/Preferences 目录中。NSUserDefaults 类来读写Preferences设置,而无需考虑文件位置等细节问题。NSUserDefaults 用起来和 NSDictionary 很相似,多了一个Domain的概念在里面。
123NSUserDefaults *userDefaults = [ NSUserDefaults standardUserDefaults ] ;[ userDefaults setBool :YES forKey : @"firstLogin" ] ;[ userDefaults synchronize ] ;NSKeyedArchiver 归档
归档在iOS中是另一种形式的序列化,只要遵循了NSCoding协议的对象都可以通过它实现序列化。
遵从NSCoding协议
NSCoding 协议声明了两个方法,这两个方法都是必须实现的。一个用于归档,一个用于解档。12345678910111213141516171819202122232425262728293031@interface PhotoInfo : CBModel@property ( nonatomic , copy ) NSString *url ;@property ( nonatomic , copy ) NSString *photoUrl ;@property ( nonatomic , assign ) int width ;@property ( nonatomic , assign ) int height ;@end- ( instancetype ) initWithCoder : ( NSCoder * ) decoder {if ( self = [ super init ] ) {self . url = [ decoder decodeObjectForKey : @"url" ] ;self . width = [ [ decoder decodeObjectForKey : @"width" ] intValue ] ;self . height = [ [ decoder decodeObjectForKey : @"height" ] intValue ] ;self . photoUrl = [ decoder decodeObjectForKey : @"photoUrl" ] ;}return self ;}- ( void ) encodeWithCoder : ( NSCoder * ) encoder {[ encoder encodeObject :self . url forKey : @"url" ] ;[ encoder encodeObject : @ ( self . width ) forKey : @"width" ] ;[ encoder encodeObject : @ ( self . height ) forKey : @"height" ] ;[ encoder encodeObject :self . photoUrl forKey : @"photoUrl" ] ;}[ NSKeyedArchiver archiveRootObject :object toFile :file ] ;[ NSKeyedUnarchiver unarchiveObjectWithFile :file ] ;SQLite3
由于本人对于数据库的操作一直采用FMDB库进行操作,一下就已该库操作为例。
SQLite是无类型的。即不管你在创表时指定的字段类型是什么,存储是依然可以存储任意类型的数据。但为了良好的编程规范和增加可读性,一般都指定类型。一般分为:- integer : 整数 主键必须设置为该类型
- real : 实数(浮点数)
- text : 文本字符串
- blob : 二进制数据,比如文件,图片之类的
FMDB
FMDB是iOS平台的SQLite数据库框架,FMDB以OC的方式封装了SQLite的C语言API。具有一下有点
- 使用起来更加面向对象,省去了很多麻烦、冗余的C语言代码
- 对比苹果自带的Core Data框架,更加轻量级和灵活
- 提供了多线程安全的数据库操作方法,有效地防止数据混乱
核心类包括FMDatabase, FMResultSet, FMDatabaseQueue这三个类。
12345678910111213141516171819202122232425262728293031323334353637// 创建表NSString *sqlCreateTalentHistoryTable = [ NSString stringWithFormat :@"create table if not exists testDB\n""(pid INTEGER PRIMARY KEY AUTOINCREMENT,\n""nickName text,\n""avatarUrl text,\n""isAdd text\n)"] ;BOOL resTalentHistory = [ self . db executeUpdate :sqlCreateTalentHistoryTable ] ;if ( ! resTalentHistory ) {NSLog ( @"error when creating CBWallet_TalentHistory table" ) ;}}// 执行更新使用 executeUpdate :方法执行更新- ( BOOL ) executeUpdate : ( NSString * ) sql , . . .- ( BOOL ) executeUpdateWithFormat : ( NSString * ) format , . . .- ( BOOL ) executeUpdate : ( NSString * ) sql withArgumentsInArray : ( NSArray * ) arguments示例[ db executeUpdate : @"UPDATE testDB SET isAdd = ? WHERE nickName = ?;" , @ YES , @"Zhao" ]// 执行查询查询方法- ( FMResultSet * ) executeQuery : ( NSString * ) sql , . . .- ( FMResultSet * ) executeQueryWithFormat : ( NSString * ) format , . . .- ( FMResultSet * ) executeQuery : ( NSString * ) sql withArgumentsInArray : ( NSArray * ) arguments示例FMResultSet *rs = [ db executeQuery : @"SELECT * FROM testDB" ] ;// 遍历结果集while ( [ rs next ] ) {NSString *name = [ rs stringForColumn : @"nickName" ] ;BOOL isAdd = [ rs intForColumn : @"isAdd" ] ;}对于数据库操作,谈论比较多的就是线程安全问题。不要让多个线程操作同一个库。为此,FMDB实现了一个FMDatabaseQueue类,以保证数据库的线程安全。
123456789101112131415161718192021// 创建队列FMDatabaseQueue *queue = [ FMDatabaseQueue databaseQueueWithPath :aPath ] ;// 使用队列[ queue inDatabase : ^ ( FMDatabase *database ) {[ database executeUpdate : @"INSERT INTO testDB(nickName, isAdd) VALUES (?, ?)" , @"Zhang" , @ YES ] ;[ database executeUpdate : @"INSERT INTO testDB(nickName, isAdd) VALUES (?, ?)" , @"Wang" , @ YES ] ;[ database executeUpdate : @"INSERT INTO testDB(nickName, isAdd) VALUES (?, ?)" , @"Lee" , @ YES ] ;FMResultSet *result = [ database executeQuery : @"select * from testDB" ] ;while ( [ result next ] ) {}} ] ;// 也可以轻松地把简单任务包装到事务里:[ queue inTransaction : ^ ( FMDatabase *database , BOOL *rollback ) {[ database executeUpdate : @"INSERT INTO testDB(nickName, isAdd) VALUES (?, ?)" , @"Zhang" , @ YES ] ;[ database executeUpdate : @"INSERT INTO testDB(nickName, isAdd) VALUES (?, ?)" , @"Zhang" , @ YES ] ;[ database executeUpdate : @"INSERT INTO testDB(nickName, isAdd) VALUES (?, ?)" , @"Zhang" , @ YES ] ;FMResultSet *result = [ database executeQuery : @"select * from testDB" ] ;while ( [ result next ] ) {}} ] ;以上内容为本人根据工作中涉及的知识点整理内容,如有侵权请与我联系。