偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

iOS中幾種數(shù)據(jù)持久化方案:我要永遠(yuǎn)地記住你!

移動開發(fā)
所謂的持久化,就是將數(shù)據(jù)保存到硬盤中,使得在應(yīng)用程序或機(jī)器重啟后可以繼續(xù)訪問之前保存的數(shù)據(jù)

 [[141204]]

概論

所謂的持久化,就是將數(shù)據(jù)保存到硬盤中,使得在應(yīng)用程序或機(jī)器重啟后可以繼續(xù)訪問之前保存的數(shù)據(jù)。在iOS開發(fā)中,有很多數(shù)據(jù)持久化的方案,接下來我將嘗試著介紹一下5種方案:

  • plist文件(屬性列表)
  • preference(偏好設(shè)置)
  • NSKeyedArchiver(歸檔)
  • SQLite 3
  • CoreData

沙盒

在介紹各種存儲方法之前,有必要說明以下沙盒機(jī)制。iOS程序默認(rèn)情況下只能訪問程序自己的目錄,這個目錄被稱為“沙盒”。

1.結(jié)構(gòu)

既然沙盒就是一個文件夾,那就看看里面有什么吧。沙盒的目錄結(jié)構(gòu)如下:

  1. "應(yīng)用程序包" 
  2. Documents 
  3. Library 
  4.     Caches 
  5.     Preferences 
  6. tmp 

2.目錄特性

雖然沙盒中有這么多文件夾,但是沒有文件夾都不盡相同,都有各自的特性。所以在選擇存放目錄時,一定要認(rèn)真選擇適合的目錄。

"應(yīng)用程序包": 這里面存放的是應(yīng)用程序的源文件,包括資源文件和可執(zhí)行文件。

  1. NSString *path = [[NSBundle mainBundle] bundlePath]; 
  2.   NSLog(@"%@", path); 

Documents: 最常用的目錄,iTunes同步該應(yīng)用時會同步此文件夾中的內(nèi)容,適合存儲重要數(shù)據(jù)。

  1. NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; 
  2.   NSLog(@"%@", path); 

Library/Caches: iTunes不會同步此文件夾,適合存儲體積大,不需要備份的非重要數(shù)據(jù)。

  1. NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject; 
  2.  NSLog(@"%@", path); 

Library/Preferences: iTunes同步該應(yīng)用時會同步此文件夾中的內(nèi)容,通常保存應(yīng)用的設(shè)置信息。

tmp: iTunes不會同步此文件夾,系統(tǒng)可能在應(yīng)用沒運(yùn)行時就刪除該目錄下的文件,所以此目錄適合保存應(yīng)用中的一些臨時文件,用完就刪除。

 
  1. NSString *path = NSTemporaryDirectory(); 
  2.   NSLog(@"%@", path); 

plist文件

plist文件是將某些特定的類,通過XML文件的方式保存在目錄中。

可以被序列化的類型只有如下幾種:

  1. NSArray; 
  2. NSMutableArray; 
  3. NSDictionary; 
  4. NSMutableDictionary; 
  5. NSData; 
  6. NSMutableData; 
  7. NSString; 
  8. NSMutableString; 
  9. NSNumber; 
  10. NSDate; 

1.獲得文件路徑

  1. NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; 
  2.     NSString *fileName = [path stringByAppendingPathComponent:@"123.plist"]; 

2.存儲

  1. NSArray *array = @[@"123", @"456", @"789"]; 
  2. [array writeToFile:fileName atomically:YES]; 

3.讀取

  1. NSArray *result = [NSArray arrayWithContentsOfFile:fileName]; 
  2. NSLog(@"%@", result); 

4.注意

  • 只有以上列出的類型才能使用plist文件存儲。
  • 存儲時使用writeToFile: atomically:方法。 其中atomically表示是否需要先寫入一個輔助文件,再把輔助文件拷貝到目標(biāo)文件地址。這是更安全的寫入文件方法,一般都寫YES。
  • 讀取時使用arrayWithContentsOfFile:方法。

Preference

1.使用方法

  1. //1.獲得NSUserDefaults文件 
  2. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
  3. //2.向文件中寫入內(nèi)容 
  4. [userDefaults setObject:@"AAA" forKey:@"a"]; 
  5. [userDefaults setBool:YES forKey:@"sex"]; 
  6. [userDefaults setInteger:21 forKey:@"age"]; 
  7. //2.1立即同步 
  8. [userDefaults synchronize]; 
  9. //3.讀取文件 
  10. NSString *name = [userDefaults objectForKey:@"a"]; 
  11. BOOL sex = [userDefaults boolForKey:@"sex"]; 
  12. NSInteger age = [userDefaults integerForKey:@"age"]; 
  13. NSLog(@"%@, %d, %ld", name, sex, age); 

2.注意

  • 偏好設(shè)置是專門用來保存應(yīng)用程序的配置信息的,一般不要在偏好設(shè)置中保存其他數(shù)據(jù)。
  • 如果沒有調(diào)用synchronize方法,系統(tǒng)會根據(jù)I/O情況不定時刻地保存到文件中。所以如果需要立即寫入文件的就必須調(diào)用synchronize方法。
  • 偏好設(shè)置會將所有數(shù)據(jù)保存到同一個文件中。即preference目錄下的一個以此應(yīng)用包名來命名的plist文件。

#p#

NSKeyedArchiver

歸檔在iOS中是另一種形式的序列化,只要遵循了NSCoding協(xié)議的對象都可以通過它實現(xiàn)序列化。由于決大多數(shù)支持存儲數(shù)據(jù)的Foundation和Cocoa Touch類都遵循了NSCoding協(xié)議,因此,對于大多數(shù)類來說,歸檔相對而言還是比較容易實現(xiàn)的。

1.遵循NSCoding協(xié)議

NSCoding協(xié)議聲明了兩個方法,這兩個方法都是必須實現(xiàn)的。一個用來說明如何將對象編碼到歸檔中,另一個說明如何進(jìn)行解檔來獲取一個新對象。

  • 遵循協(xié)議和設(shè)置屬性
  1. //1.遵循NSCoding協(xié)議  
  2.   @interface Person : NSObject   //2.設(shè)置屬性 
  3.   @property (strong, nonatomic) UIImage *avatar; 
  4.   @property (copy, nonatomic) NSString *name; 
  5.   @property (assign, nonatomic) NSInteger age; 
  6.   @end 
  • 實現(xiàn)協(xié)議方法
  1. //解檔 
  2.   - (id)initWithCoder:(NSCoder *)aDecoder { 
  3.       if ([super init]) { 
  4.           self.avatar = [aDecoder decodeObjectForKey:@"avatar"]; 
  5.           self.name = [aDecoder decodeObjectForKey:@"name"]; 
  6.           self.age = [aDecoder decodeIntegerForKey:@"age"]; 
  7.       } 
  8.       return self; 
  9.   } 
  10.   //歸檔 
  11.   - (void)encodeWithCoder:(NSCoder *)aCoder { 
  12.       [aCoder encodeObject:self.avatar forKey:@"avatar"]; 
  13.       [aCoder encodeObject:self.name forKey:@"name"]; 
  14.       [aCoder encodeInteger:self.age forKey:@"age"]; 
  15.   } 
 
  • 特別注意

如果需要?dú)w檔的類是某個自定義類的子類時,就需要在歸檔和解檔之前先實現(xiàn)父類的歸檔和解檔方法。即 [super encodeWithCoder:aCoder] 和 [super initWithCoder:aDecoder] 方法;

2.使用

需要把對象歸檔是調(diào)用NSKeyedArchiver的工廠方法 archiveRootObject: toFile: 方法。

 
  1. NSString *file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"]; 
  2.   Person *person = [[Person alloc] init]; 
  3.   person.avatar = self.avatarView.image; 
  4.   person.name = self.nameField.text; 
  5.   person.age = [self.ageField.text integerValue]; 
  6.   [NSKeyedArchiver archiveRootObject:person toFile:file]; 

需要從文件中解檔對象就調(diào)用NSKeyedUnarchiver的一個工廠方法 unarchiveObjectWithFile: 即可。

 
  1. NSString *file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"]; 
  2.   Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:file]; 
  3.   if (person) { 
  4.      self.avatarView.image = person.avatar; 
  5.      self.nameField.text = person.name; 
  6.      self.ageField.text = [NSString stringWithFormat:@"%ld", person.age]; 
  7.   } 

3.注意

  • 必須遵循并實現(xiàn)NSCoding協(xié)議

  • 保存文件的擴(kuò)展名可以任意指定

  • 繼承時必須先調(diào)用父類的歸檔解檔方法

SQLite3

之前的所有存儲方法,都是覆蓋存儲。如果想要增加一條數(shù)據(jù)就必須把整個文件讀出來,然后修改數(shù)據(jù)后再把整個內(nèi)容覆蓋寫入文件。所以它們都不適合存儲大量的內(nèi)容。

1.字段類型

表面上SQLite將數(shù)據(jù)分為以下幾種類型:

  • integer : 整數(shù)
  • real : 實數(shù)(浮點(diǎn)數(shù))
  • text : 文本字符串
  • blob : 二進(jìn)制數(shù)據(jù),比如文件,圖片之類的

實際上SQLite是無類型的。即不管你在創(chuàng)表時指定的字段類型是什么,存儲是依然可以存儲任意類型的數(shù)據(jù)。而且在創(chuàng)表時也可以不指定字段類型。SQLite之所以什么類型就是為了良好的編程規(guī)范和方便開發(fā)人員交流,所以平時在使用時最好設(shè)置正確的字段類型!主鍵必須設(shè)置成integer

2. 準(zhǔn)備工作

準(zhǔn)備工作就是導(dǎo)入依賴庫啦,在iOS中要使用SQLite3,需要添加庫文件:libsqlite3.dylib并導(dǎo)入主頭文件,這是一個C語言的庫,所以直接使用SQLite3還是比較麻煩的。

3.使用

  • 創(chuàng)建數(shù)據(jù)庫并打開

操作數(shù)據(jù)庫之前必須先指定數(shù)據(jù)庫文件和要操作的表,所以使用SQLite3,首先要打開數(shù)據(jù)庫文件,然后指定或創(chuàng)建一張表。

  1. /** 
  2. *  打開數(shù)據(jù)庫并創(chuàng)建一個表 
  3. */ 
  4. - (void)openDatabase { 
  5.    //1.設(shè)置文件名 
  6.    NSString *filename = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.db"]; 
  7.    //2.打開數(shù)據(jù)庫文件,如果沒有會自動創(chuàng)建一個文件 
  8.    NSInteger result = sqlite3_open(filename.UTF8String, &_sqlite3); 
  9.    if (result == SQLITE_OK) { 
  10.        NSLog(@"打開數(shù)據(jù)庫成功!"); 
  11.        //3.創(chuàng)建一個數(shù)據(jù)庫表 
  12.        char *errmsg = NULL; 
  13.        sqlite3_exec(_sqlite3, "CREATE TABLE IF NOT EXISTS t_person(id integer primary key autoincrement, name text, age integer)", NULL, NULL, &errmsg); 
  14.        if (errmsg) { 
  15.            NSLog(@"錯誤:%s", errmsg); 
  16.        } else { 
  17.            NSLog(@"創(chuàng)表成功!"); 
  18.        } 
  19.    } else { 
  20.        NSLog(@"打開數(shù)據(jù)庫失敗!"); 
  21.    } 
  • 執(zhí)行指令

使用 sqlite3_exec() 方法可以執(zhí)行任何SQL語句,比如創(chuàng)表、更新、插入和刪除操作。但是一般不用它執(zhí)行查詢語句,因為它不會返回查詢到的數(shù)據(jù)。

  1. /** 
  2. *  往表中插入1000條數(shù)據(jù) 
  3. */ 
  4. - (void)insertData { 
  5. NSString *nameStr; 
  6. NSInteger age; 
  7. for (NSInteger i = 0; i < 1000; i++) { 
  8.   nameStr = [NSString stringWithFormat:@"Bourne-%d", arc4random_uniform(10000)]; 
  9.   age = arc4random_uniform(80) + 20
  10.   NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_person (name, age) VALUES('%@', '%ld')", nameStr, age]; 
  11.   char *errmsg = NULL; 
  12.   sqlite3_exec(_sqlite3, sql.UTF8String, NULL, NULL, &errmsg); 
  13.   if (errmsg) { 
  14.       NSLog(@"錯誤:%s", errmsg); 
  15.   } 
  16. NSLog(@"插入完畢!"); 
 
  • 查詢指令

前面說過一般不使用 sqlite3_exec() 方法查詢數(shù)據(jù)。因為查詢數(shù)據(jù)必須要獲得查詢結(jié)果,所以查詢相對比較麻煩。示例代碼如下:

    • 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

 
  1. /** 
  2. *  從表中讀取數(shù)據(jù)到數(shù)組中 
  3. */ 
  4. - (void)readData { 
  5.    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:1000]; 
  6.    char *sql = "select name, age from t_person;"
  7.    sqlite3_stmt *stmt; 
  8.    NSInteger result = sqlite3_prepare_v2(_sqlite3, sql, -1, &stmt, NULL); 
  9.    if (result == SQLITE_OK) { 
  10.        while (sqlite3_step(stmt) == SQLITE_ROW) { 
  11.            char *name = (char *)sqlite3_column_text(stmt, 0); 
  12.            NSInteger age = sqlite3_column_int(stmt, 1); 
  13.            //創(chuàng)建對象 
  14.            Person *person = [Person personWithName:[NSString stringWithUTF8String:name] Age:age]; 
  15.            [mArray addObject:person]; 
  16.        } 
  17.        self.dataList = mArray; 
  18.    } 
  19.    sqlite3_finalize(stmt); 

4.總結(jié)

總得來說,SQLite3的使用還是比較麻煩的,因為都是些c語言的函數(shù),理解起來有些困難。不過在一般開發(fā)過程中,使用的都是第三方開源庫 FMDB,封裝了這些基本的c語言方法,使得我們在使用時更加容易理解,提高開發(fā)效率。

#p#

FMDB

1.簡介

FMDB是iOS平臺的SQLite數(shù)據(jù)庫框架,它是以O(shè)C的方式封裝了SQLite的C語言API,它相對于cocoa自帶的C語言框架有如下的優(yōu)點(diǎn):

使用起來更加面向?qū)ο?,省去了很多麻煩、冗余的C語言代碼

對比蘋果自帶的Core Data框架,更加輕量級和靈活

提供了多線程安全的數(shù)據(jù)庫操作方法,有效地防止數(shù)據(jù)混亂

注:FMDB的gitHub地址

2.核心類

FMDB有三個主要的類:

  • FMDatabase

一個FMDatabase對象就代表一個單獨(dú)的SQLite數(shù)據(jù)庫,用來執(zhí)行SQL語句

  • FMResultSet

使用FMDatabase執(zhí)行查詢后的結(jié)果集

  • FMDatabaseQueue

用于在多線程中執(zhí)行多個查詢或更新,它是線程安全的

3.打開數(shù)據(jù)庫

和c語言框架一樣,F(xiàn)MDB通過指定SQLite數(shù)據(jù)庫文件路徑來創(chuàng)建FMDatabase對象,但FMDB更加容易理解,使用起來更容易,使用之前一樣需要導(dǎo)入sqlite3.dylib。打開數(shù)據(jù)庫方法如下:

  1. NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.db"]; 
  2. FMDatabase *database = [FMDatabase databaseWithPath:path];     
  3. if (![database open]) { 
  4.     NSLog(@"數(shù)據(jù)庫打開失??!"); 

值得注意的是,Path的值可以傳入以下三種情況:

  • 具體文件路徑,如果不存在會自動創(chuàng)建
  • 空字符串@"",會在臨時目錄創(chuàng)建一個空的數(shù)據(jù)庫,當(dāng)FMDatabase連接關(guān)閉時,數(shù)據(jù)庫文件也被刪除
  • nil,會創(chuàng)建一個內(nèi)存中臨時數(shù)據(jù)庫,當(dāng)FMDatabase連接關(guān)閉時,數(shù)據(jù)庫會被銷毀

4.更新

在FMDB中,除查詢以外的所有操作,都稱為“更新”, 如:create、drop、insert、update、delete等操作,使用executeUpdate:方法執(zhí)行更新:

 
  1. //常用方法有以下3種:    
  2. - (BOOL)executeUpdate:(NSString*)sql, ... 
  3. - (BOOL)executeUpdateWithFormat:(NSString*)format, ... 
  4. - (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments 
  5. //示例 
  6. [database executeUpdate:@"CREATE TABLE IF NOT EXISTS t_person(id integer primary key autoincrement, name text, age integer)"];    
  7. //或者   
  8. [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES(?, ?)", @"Bourne", [NSNumber numberWithInt:42]]; 

5.查詢

查詢方法也有3種,使用起來相當(dāng)簡單:

  1. - (FMResultSet *)executeQuery:(NSString*)sql, ... 
  2. - (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... 
  3. - (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments 

查詢示例:

  1. //1.執(zhí)行查詢 
  2. FMResultSet *result = [database executeQuery:@"SELECT * FROM t_person"]; 
  3. //2.遍歷結(jié)果集 
  4. while ([result next]) { 
  5.     NSString *name = [result stringForColumn:@"name"]; 
  6.     int age = [result intForColumn:@"age"]; 

6.線程安全

在多個線程中同時使用一個FMDatabase實例是不明智的。不要讓多個線程分享同一個FMDatabase實例,它無法在多個線程中同時使用。 如果在多個線程中同時使用一個FMDatabase實例,會造成數(shù)據(jù)混亂等問題。所以,請使用 FMDatabaseQueue,它是線程安全的。以下是使用方法:

  • 創(chuàng)建隊列。

  1. FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; 
  • 使用隊列

 
  1. [queue inDatabase:^(FMDatabase *database) {     
  2.           [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_1", [NSNumber numberWithInt:1]];     
  3.           [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_2", [NSNumber numberWithInt:2]];     
  4.           [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_3", [NSNumber numberWithInt:3]];       
  5.           FMResultSet *result = [database executeQuery:@"select * from t_person"];     
  6.          while([result next]) {    
  7.          }     
  8. }]; 

而且可以輕松地把簡單任務(wù)包裝到事務(wù)里:

 
  1. [queue inTransaction:^(FMDatabase *database, BOOL *rollback) {     
  2.           [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_1", [NSNumber numberWithInt:1]];     
  3.           [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_2", [NSNumber numberWithInt:2]];     
  4.           [database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_3", [NSNumber numberWithInt:3]];       
  5.           FMResultSet *result = [database executeQuery:@"select * from t_person"];     
  6.              while([result next]) {    
  7.              }    
  8.            //回滾 
  9.            *rollback = YES;   
  10.     }]; 

FMDatabaseQueue 后臺會建立系列化的G-C-D隊列,并執(zhí)行你傳給G-C-D隊列的塊。這意味著 你從多線程同時調(diào)用調(diào)用方法,GDC也會按它接收的塊的順序來執(zhí)行。

責(zé)任編輯:倪明 來源: 伯恩的遺產(chǎn)的簡書
相關(guān)推薦

2015-07-20 09:26:09

iOS數(shù)據(jù)庫存儲

2021-03-03 00:01:30

Redis數(shù)據(jù)結(jié)雙向鏈表

2015-10-15 09:54:31

應(yīng)用架構(gòu)本地化iOS

2013-09-12 14:56:02

iOS持久化

2023-10-31 21:26:01

Prompt順序人工智能

2019-09-05 09:15:50

數(shù)據(jù)容器Docker

2015-09-01 10:29:44

數(shù)據(jù)安全

2019-02-26 14:39:20

Windows后門漏洞

2019-05-15 09:44:33

數(shù)據(jù)Redis持久化

2023-12-29 08:19:52

應(yīng)用程序開發(fā)者數(shù)據(jù)庫

2019-05-15 09:04:47

Redis數(shù)據(jù)存儲數(shù)據(jù)

2017-09-21 08:16:33

數(shù)據(jù)存儲環(huán)境

2019-11-18 16:20:48

RedisRDB數(shù)據(jù)庫

2019-04-15 14:05:56

MySQLUTF-8數(shù)據(jù)庫

2021-03-18 08:18:15

ZooKeeper數(shù)據(jù)持久化

2021-09-02 09:53:42

開發(fā)Redis配置

2024-05-27 09:07:27

2020-07-10 06:11:19

數(shù)據(jù)庫擴(kuò)展負(fù)載

2009-11-18 13:41:42

路由器分類

2020-11-16 09:15:07

MYSQL
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號