IOS數(shù)據(jù)持久化
數(shù)據(jù)的持久化,就是將數(shù)據(jù)保存到硬盤中,使得在應(yīng)用程序或機器重啟后可以繼續(xù)訪問之前保存的數(shù)據(jù)。在iOS開發(fā)中,有很多數(shù)據(jù)持久化的方案,本文將先對IOS沙盒文件進行簡單介紹,然后分析plist文件、歸檔、偏好設(shè)置、數(shù)據(jù)庫四種常用的方案。
沙盒介紹
Apple為了安全考慮,限制IOS應(yīng)用程序默認情況下只能訪問程序自己的目錄,這個目錄被稱為“沙盒”。
- 應(yīng)用程序在自己的沙盒中運作,但是不能訪問任何其他應(yīng)用程序的沙盒;
- 應(yīng)用之間不能共享數(shù)據(jù),沙盒里的文件不能被復(fù)制到其他應(yīng)用程序的文件夾中,也不能把其他應(yīng)用文件夾復(fù)制到沙盒中;
- 蘋果禁止任何讀寫沙盒以外的文件,禁止應(yīng)用程序?qū)?nèi)容寫到沙盒以外的文件夾中。
結(jié)構(gòu)
沙盒的目錄結(jié)構(gòu)如下:
- "應(yīng)用程序包"
- Documents
- Library
- Caches
- Preferences
- tmp
特性
沙盒中的每個文件夾都各盡不同,所以在選擇數(shù)據(jù)存儲時需要選擇合適的目錄
"應(yīng)用程序包":
應(yīng)用程序包里面存放的主要是應(yīng)用程序的源文件,包括可執(zhí)行文件和資源文件,其路徑獲取方式如下:
NSString *path = [[NSBundle mainBundle] bundlePath];
Documents:
Documents是最常用的目錄,iTunes會同步此文件夾的內(nèi)容,適合存儲重要的數(shù)據(jù),其路徑獲取方式如下:
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
Library/Caches:
Library/Caches,iTnues不會同步此文件夾中的內(nèi)容,通常適合存儲體積大,不需要備份的非重要數(shù)據(jù),其路徑獲取方式如下:
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
Library/Preferences:
Library/Preferences,iTunes會同步此文件夾中的內(nèi)容,通常用于保存應(yīng)用的設(shè)置信息,其獲取方式如下:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
tmp:
tmp,iTunes不會同步此文件夾,系統(tǒng)可能在應(yīng)用沒有運行時刪除該目錄下的文件,適合保存應(yīng)用中的一些臨時文件,用完就刪除,起路徑獲取方式如下:
NSString *path = NSTemporaryDirectory();
持久化方式
IOS 應(yīng)用程序常用的數(shù)據(jù)持久化方法主要有plist文件(屬性列表)、歸檔(NSKeyedArchiver)、偏好設(shè)置(preference)、數(shù)據(jù)庫(SQL、CoreData)。
plist文件
plist文件是將IOS中一些特定的類,通過XML文件的方式持久化在本地目錄中??梢员恍蛄谢念愔挥蠥pple系統(tǒng)提供的以下幾種:
NSString
NSMutableString
NSData
NSMutableData
NSArray
NSMutableArray
NSDictionary
NSMutableDictionary
NSNumber
NSDate
- 使用示例
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *plistFilePath = [path stringByAppendingString:@"/testPlist.plist"];
//存儲
NSDictionary *dict = @{@"1":@"one",@"2":@"two",@"3":@"three"};
[dict writeToFile:plistFilePath atomically:YES];
//讀取
NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:plistFilePath];
NSLog(@"read content is %@", readDict);
- 注意事項
- 只有以上類型才能使用plist文件存儲,無論文件命名或者存儲位置如何,序列化均為XML
- writeToFile: atomically:方法。 其中atomically表示是否需要先寫入一個輔助文件,再把輔助文件拷貝到目標文件地址。這是更安全的寫入文件方法,一般都寫YES。
- 讀取時用XXXWithContentsOfFile:方法
歸檔
歸檔在iOS中是另一種形式的序列化,只要遵循了NSCoding協(xié)議實現(xiàn)了initWithCoder:和encodeWithCoder:方法的對象都可以通過它實現(xiàn)序列化,存儲在文件中。
- 使用示例
@class Student;
@interface ClassRoom : NSObject <NSCoding>
@property (nonatomic, strong) NSString *grade;
@property (nonatomic, strong) NSArray<Student *> *students;
@end
@implementation ClassRoom
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
self.grade = [aDecoder decodeObjectForKey:@"grade"];
self.students = [aDecoder decodeObjectForKey:@"students"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.grade forKey:@"grade"];
[aCoder encodeObject:self.students forKey:@"students"];
}
@end
@interface Student : NSObject <NSCoding>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger sID;
@end
@implementation Student
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.sID = [[aDecoder decodeObjectForKey:@"sID"] integerValue];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:[NSNumber numberWithInteger:self.sID] forKey:@"sID"];
}
@end
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *archiverPath = [path stringByAppendingString:@"/classRoom.data"];
NSMutableArray *studentArray = [NSMutableArray array];
for (NSInteger i = 0; i < 10; i++) {
Student *student = [[Student alloc] init];
student.name = [NSString stringWithFormat:@"student%zd", i];
student.sID = i;
[studentArray addObject:student];
}
ClassRoom *classRoom = [[ClassRoom alloc] init];
classRoom.grade = @"grade one";
classRoom.students = studentArray;
//存儲
[NSKeyedArchiver archiveRootObject:classRoom toFile:archiverPath];
//讀取
ClassRoom *readClassRoom = [NSKeyedUnarchiver unarchiveObjectWithFile:archiverPath];
- 注意事項
- 如果需要歸檔的類中包含某個屬性是自定義的類的實例,則需要相應(yīng)的類也實現(xiàn)NSCoding協(xié)議,如示例中的Student。
- 保存文件的擴展名可以任意指定。
- 如果需要歸檔的類是某個自定義類的子類時,就需要在歸檔和解檔之前先實現(xiàn)父類的歸檔和解檔方法。即 [super encodeWithCoder:aCoder] 和 [super initWithCoder:aDecoder] 方法。
偏好設(shè)置
NSUserDefaults類提供了與默認數(shù)據(jù)庫相交互的編程接口。其實它存儲在應(yīng)用程序的一個plist文件里,路徑為沙盒Document目錄平級的/Library/Prefereces里。如果將默認數(shù)據(jù)庫比喻為SQL數(shù)據(jù)庫,那么NSUserDefaults就相當(dāng)于SQL語句。
NSUserDefaults支持的數(shù)據(jù)類型有:NSNumber(NSInteger、float、double),NSString,NSDate,NSArray,NSDictionary,BOOL,NSData
- 使用示例
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//存儲
[userDefaults setObject:@"one" forKey:@"1"];
[userDefaults setInteger:2 forKey:@"2"];
[userDefaults setBool:YES forKey:@"3"];
//立即同步
[userDefaults synchronize];
//讀取
NSString *one = [userDefaults objectForKey:@"1"];
NSInteger two = [userDefaults integerForKey:@"2"];
BOOL three = [userDefaults boolForKey:@"3"];
- 注意事項
- 偏好設(shè)置會把所有數(shù)據(jù)保存到Library/Preference目錄下以應(yīng)用包命名的plist文件中。
- synchronize方法讓存儲立即生效,如果沒有調(diào)用,則系統(tǒng)會I/O情況不定時地保存。
- 偏好設(shè)置是專門用來保存應(yīng)用程序的配置信息的,一般不要在偏好設(shè)置中保存其他數(shù)據(jù)。
數(shù)據(jù)庫
以上三種存儲方法都是覆蓋存儲,如果數(shù)據(jù)量比較大,則需要數(shù)據(jù)庫操作。IOS應(yīng)用程序中常用的有SQLite和CoreDada。
SQLite
SQLite是基于C語言開發(fā)的輕型數(shù)據(jù)庫,在iOS中需要使用C語言語法進行數(shù)據(jù)庫操作、訪問(無法使用ObjC直接訪問,因為libqlite3框架基于C語言編寫),SQLite中采用的是動態(tài)數(shù)據(jù)類型,即使創(chuàng)建時定義了一種類型,在實際操作時也可以存儲其他類型,但是推薦建庫時使用合適的類型(特別是應(yīng)用需要考慮跨平臺的情況時),建立連接后通常不需要關(guān)閉連接(盡管可以手動關(guān)閉)。
- 使用示例
@interface PersistentDemo ()
{
sqlite3 *db;
}
- (void)testSqlite{
//創(chuàng)建數(shù)據(jù)庫
[self createDb:@"personInfo.sqlite"];
//創(chuàng)建表
NSString *sqlCreateTable = @"CREATE TABLE personInfo (ID INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, address TEXT)";
[self execSql:sqlCreateTable];
//插入
NSString *insertOne = [NSString stringWithFormat:@"INSERT INTO '%@' (name, age, address) VALUES ('%@', '%@', '%@')", @"personInfo", @"張三", @"20", @"西湖區(qū)"];
NSString *insertTwo = [NSString stringWithFormat:@"INSERT INTO '%@' (name, age, address) VALUES ('%@', '%@', '%@')", @"personInfo", @"李四", @"26", @"濱江區(qū)"];
[self execSql:insertOne];
[self execSql:insertTwo];
//查詢數(shù)據(jù)
NSString *search = [NSString stringWithFormat:@"SELECT * FROM '%@' WHERE name='%@'", @"personInfo", @"張三"];
[self execSearchSql:search];
[self closeDb];
}
- (void)createDb:(NSString *)name{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *dbName = [path stringByAppendingPathComponent:name];
if (sqlite3_open([dbName UTF8String], &db) != SQLITE_OK) {
sqlite3_close(db);
NSLog(@"數(shù)據(jù)庫打開失敗");
}
}
- (void)execSql:(NSString *)sql{
char *err;
if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
sqlite3_close(db);
NSLog(@"數(shù)據(jù)庫操作失敗");
}
}
- (void)execSearchSql:(NSString *)sql{
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
char *name = (char *)sqlite3_column_text(statement, 1);
NSString *nsNameStr = [[NSString alloc] initWithUTF8String:name];
int age = sqlite3_column_int(statement, 2);
char *address = (char *)sqlite3_column_text(statement, 3);
NSString *nsAddrerss = [[NSString alloc] initWithUTF8String:address];
NSLog(@"name :%@, age: %d, address: %@", nsNameStr, age, nsAddrerss);
}
}
sqlite3_finalize(statement);
}
- (void)closeDb{
sqlite3_close(db);
}
- 注意事項
- 需要導(dǎo)入依賴庫,添加庫文件libsqlite3.dylib并導(dǎo)入主頭文件
- CRUD中需要對查詢進行單獨處理
- sqlite3_prepare_v2() : 檢查sql的合法性
- sqlite3_step() : 逐行獲取查詢結(jié)果,不斷重復(fù),直到最后一條記錄
- sqlite3_coloum_xxx() : 獲取對應(yīng)類型的內(nèi)容,iCol對應(yīng)的就是SQL語句中字段的順序,從0開始。根據(jù)實際查詢字段的屬性,使用sqlite3_column_xxx取得對應(yīng)的內(nèi)容即可。
- sqlite3_finalize() : 釋放stmt。
- SQLite使用比較麻煩,可以使用基于其封裝的FMDB
CoreData
CoreData 有空再單獨整理,此處僅列出持久化調(diào)度邏輯關(guān)系圖。
