本文轉(zhuǎn)自iOS中幾種數(shù)據(jù)持久化方案,僅用作個(gè)人記錄學(xué)習(xí)之用。
概論
所謂的持久化,就是將數(shù)據(jù)保存到硬盤(pán)中,使得在應(yīng)用程序或機(jī)器重啟后可以繼續(xù)訪(fǎng)問(wèn)之前保存的數(shù)據(jù)。在iOS開(kāi)發(fā)中,有很多數(shù)據(jù)持久化的方案,接下來(lái)我將嘗試著介紹一下5種方案:
plist文件(屬性列表)
preference(偏好設(shè)置)
NSKeyedArchiver(歸檔)
SQLite3
CoreData
沙盒
在介紹各種存儲(chǔ)方法之前,有必要說(shuō)明以下沙盒機(jī)制。iOS程序默認(rèn)情況下只能訪(fǎng)問(wèn)程序自己的目錄,這個(gè)目錄被稱(chēng)為“沙盒”。
1.結(jié)構(gòu)
既然沙盒就是一個(gè)文件夾,那就看看里面有什么吧。沙盒的目錄結(jié)構(gòu)如下:
"應(yīng)用程序包"
Documents
Library
Caches
Preferences
tmp
2.目錄特性
雖然沙盒中有這么多文件夾,但是沒(méi)有文件夾都不盡相同,都有各自的特性。所以在選擇存放目錄時(shí),一定要認(rèn)真選擇適合的目錄。
-
"應(yīng)用程序包": 這里面存放的是應(yīng)用程序的源文件,包括資源文件和可執(zhí)行文件。
NSString *path = [[NSBundle mainBundle] bundlePath]; NSLog(@"%@", path); -
Documents: 最常用的目錄,iTunes同步該應(yīng)用時(shí)會(huì)同步此文件夾中的內(nèi)容,適合存儲(chǔ)重要數(shù)據(jù)。
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject; NSLog(@"%@", path); -
Library/Caches: iTunes不會(huì)同步此文件夾,適合存儲(chǔ)體積大,不需要備份的非重要數(shù)據(jù)。
NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject; NSLog(@"%@", path); Library/Preferences: iTunes同步該應(yīng)用時(shí)會(huì)同步此文件夾中的內(nèi)容,通常保存應(yīng)用的設(shè)置信息。
-
tmp: iTunes不會(huì)同步此文件夾,系統(tǒng)可能在應(yīng)用沒(méi)運(yùn)行時(shí)就刪除該目錄下的文件,所以此目錄適合保存應(yīng)用中的一些臨時(shí)文件,用完就刪除。
NSString *path = NSTemporaryDirectory(); NSLog(@"%@", path);
Plist文件
plist文件是將某些特定的類(lèi),通過(guò)XML文件的方式保存在目錄中。
可以被序列化的類(lèi)型只有如下幾種:
NSArray;
NSMutableArray;
NSDictionary;
NSMutableDictionary;
NSData;
NSMutableData;
NSString;
NSMutableString;
NSNumber;
NSDate;
1.獲得文件路徑
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *fileName = [path stringByAppendingPathComponent:@"123.plist"];
2.存儲(chǔ)
NSArray *array = @[@"123", @"456", @"789"];
[array writeToFile:fileName atomically:YES];
3.讀取
NSArray *result = [NSArray arrayWithContentsOfFile:fileName];
NSLog(@"%@", result);
4.注意
只有以上列出的類(lèi)型才能使用plist文件存儲(chǔ)。
存儲(chǔ)時(shí)使用writeToFile: atomically:方法。 其中atomically表示是否需要先寫(xiě)入一個(gè)輔助文件,再把輔助文件拷貝到目標(biāo)文件地址。這是更安全的寫(xiě)入文件方法,一般都寫(xiě)YES。
讀取時(shí)使用arrayWithContentsOfFile:方法。
Preference
1.使用方法
//1.獲得NSUserDefaults文件
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//2.向文件中寫(xiě)入內(nèi)容
[userDefaults setObject:@"AAA" forKey:@"a"];
[userDefaults setBool:YES forKey:@"sex"];
[userDefaults setInteger:21 forKey:@"age"];
//2.1立即同步
[userDefaults synchronize];
//3.讀取文件
NSString *name = [userDefaults objectForKey:@"a"];
BOOL sex = [userDefaults boolForKey:@"sex"];
NSInteger age = [userDefaults integerForKey:@"age"];
NSLog(@"%@, %d, %ld", name, sex, age);
2.注意
- 偏好設(shè)置是專(zhuān)門(mén)用來(lái)保存應(yīng)用程序的配置信息的,一般不要在偏好設(shè)置中保存其他數(shù)據(jù)。
- 如果沒(méi)有調(diào)用
synchronize方法,系統(tǒng)會(huì)根據(jù)I/O情況不定時(shí)刻地保存到文件中。所以如果需要立即寫(xiě)入文件的就必須調(diào)用synchronize方法。 - 偏好設(shè)置會(huì)將所有數(shù)據(jù)保存到同一個(gè)文件中。即
preference目錄下的一個(gè)以此應(yīng)用包名來(lái)命名的plist文件。
NSKeyedArchiver
歸檔在iOS中是另一種形式的序列化,只要遵循了NSCoding協(xié)議的對(duì)象都可以通過(guò)它實(shí)現(xiàn)序列化。由于決大多數(shù)支持存儲(chǔ)數(shù)據(jù)的Foundation和Cocoa Touch類(lèi)都遵循了NSCoding協(xié)議,因此,對(duì)于大多數(shù)類(lèi)來(lái)說(shuō),歸檔相對(duì)而言還是比較容易實(shí)現(xiàn)的。
1.遵循NSCoding協(xié)議
NSCoding協(xié)議聲明了兩個(gè)方法,這兩個(gè)方法都是必須實(shí)現(xiàn)的。一個(gè)用來(lái)說(shuō)明如何將對(duì)象編碼到歸檔中,另一個(gè)說(shuō)明如何進(jìn)行解檔來(lái)獲取一個(gè)新對(duì)象。
- 遵循協(xié)議和設(shè)置屬性
//1.遵循NSCoding協(xié)議
@interface Person : NSObject <NSCoding>
//2.設(shè)置屬性
@property (strong, nonatomic) UIImage *avatar;
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) NSInteger age;
@end
- 實(shí)現(xiàn)協(xié)議方法
//解檔
- (id)initWithCoder:(NSCoder *)aDecoder {
if ([super init]) {
self.avatar = [aDecoder decodeObjectForKey:@"avatar"];
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
}
return self;
}
//歸檔
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.avatar forKey:@"avatar"];
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
}
- 特別注意
如果需要?dú)w檔的類(lèi)是某個(gè)自定義類(lèi)的子類(lèi)時(shí),就需要在歸檔和解檔之前先實(shí)現(xiàn)父類(lèi)的歸檔和解檔方法。即[super encodeWithCoder:aCoder]和[super initWithCoder:aDecoder]方法;
2.使用
- 需要把對(duì)象歸檔是調(diào)用
NSKeyedArchiver的工廠(chǎng)方法archiveRootObject: toFile:方法。
NSString *file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"];
Person *person = [[Person alloc] init];
person.avatar = self.avatarView.image;
person.name = self.nameField.text;
person.age = [self.ageField.text integerValue];
[NSKeyedArchiver archiveRootObject:person toFile:file];
- 需要從文件中解檔對(duì)象就調(diào)用
NSKeyedUnarchiver的一個(gè)工廠(chǎng)方法unarchiveObjectWithFile:即可。
NSString *file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"];
Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:file];
if (person) {
self.avatarView.image = person.avatar;
self.nameField.text = person.name;
self.ageField.text = [NSString stringWithFormat:@"%ld", person.age];
}
3.注意
- 必須遵循并實(shí)現(xiàn)NSCoding協(xié)議
- 保存文件的擴(kuò)展名可以任意指定
- 繼承時(shí)必須先調(diào)用父類(lèi)的歸檔解檔方法
SQLite3
之前的所有存儲(chǔ)方法,都是覆蓋存儲(chǔ)。如果想要增加一條數(shù)據(jù)就必須把整個(gè)文件讀出來(lái),然后修改數(shù)據(jù)后再把整個(gè)內(nèi)容覆蓋寫(xiě)入文件。所以它們都不適合存儲(chǔ)大量的內(nèi)容。
1.字段類(lèi)型
表面上SQLite將數(shù)據(jù)分為以下幾種類(lèi)型:
integer : 整數(shù)
real : 實(shí)數(shù)(浮點(diǎn)數(shù))
text : 文本字符串
blob : 二進(jìn)制數(shù)據(jù),比如文件,圖片之類(lèi)的
實(shí)際上SQLite是無(wú)類(lèi)型的。即不管你在創(chuàng)表時(shí)指定的字段類(lèi)型是什么,存儲(chǔ)是依然可以存儲(chǔ)任意類(lèi)型的數(shù)據(jù)。而且在創(chuàng)表時(shí)也可以不指定字段類(lèi)型。SQLite之所以什么類(lèi)型就是為了良好的編程規(guī)范和方便開(kāi)發(fā)人員交流,所以平時(shí)在使用時(shí)最好設(shè)置正確的字段類(lèi)型!主鍵必須設(shè)置成integer。
2. 準(zhǔn)備工作
準(zhǔn)備工作就是導(dǎo)入依賴(lài)庫(kù)啦,在iOS中要使用SQLite3,需要添加庫(kù)文件:libsqlite3.dylib并導(dǎo)入主頭文件,這是一個(gè)C語(yǔ)言的庫(kù),所以直接使用SQLite3還是比較麻煩的。
3.使用
-
創(chuàng)建數(shù)據(jù)庫(kù)并打開(kāi)
操作數(shù)據(jù)庫(kù)之前必須先指定數(shù)據(jù)庫(kù)文件和要操作的表,所以使用SQLite3,首先要打開(kāi)數(shù)據(jù)庫(kù)文件,然后指定或創(chuàng)建一張表。
/**
* 打開(kāi)數(shù)據(jù)庫(kù)并創(chuàng)建一個(gè)表
*/
- (void)openDatabase {
//1.設(shè)置文件名
NSString *filename = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.db"];
//2.打開(kāi)數(shù)據(jù)庫(kù)文件,如果沒(méi)有會(huì)自動(dòng)創(chuàng)建一個(gè)文件
NSInteger result = sqlite3_open(filename.UTF8String, &_sqlite3);
if (result == SQLITE_OK) {
NSLog(@"打開(kāi)數(shù)據(jù)庫(kù)成功!");
//3.創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)表
char *errmsg = NULL;
sqlite3_exec(_sqlite3, "CREATE TABLE IF NOT EXISTS t_person(id integer primary key autoincrement, name text, age integer)", NULL, NULL, &errmsg);
if (errmsg) {
NSLog(@"錯(cuò)誤:%s", errmsg);
} else {
NSLog(@"創(chuàng)表成功!");
}
} else {
NSLog(@"打開(kāi)數(shù)據(jù)庫(kù)失?。?);
}
}
-
執(zhí)行指令
使用
sqlite3_exec()方法可以執(zhí)行任何SQL語(yǔ)句,比如創(chuàng)表、更新、插入和刪除操作。但是一般不用它執(zhí)行查詢(xún)語(yǔ)句,因?yàn)樗粫?huì)返回查詢(xún)到的數(shù)據(jù)。
/**
* 往表中插入1000條數(shù)據(jù)
*/
- (void)insertData {
NSString *nameStr;
NSInteger age;
for (NSInteger i = 0; i < 1000; i++) {
nameStr = [NSString stringWithFormat:@"Bourne-%d", arc4random_uniform(10000)];
age = arc4random_uniform(80) + 20;
NSString *sql = [NSString stringWithFormat:@"INSERT INTO t_person (name, age) VALUES('%@', '%ld')", nameStr, age];
char *errmsg = NULL;
sqlite3_exec(_sqlite3, sql.UTF8String, NULL, NULL, &errmsg);
if (errmsg) {
NSLog(@"錯(cuò)誤:%s", errmsg);
}
}
NSLog(@"插入完畢!");
}
-
查詢(xún)指令
前面說(shuō)過(guò)一般不使用 sqlite3_exec() 方法查詢(xún)數(shù)據(jù)。因?yàn)椴樵?xún)數(shù)據(jù)必須要獲得查詢(xún)結(jié)果,所以查詢(xún)相對(duì)比較麻煩。示例代碼如下:
sqlite3_prepare_v2() : 檢查sql的合法性
sqlite3_step() : 逐行獲取查詢(xún)結(jié)果,不斷重復(fù),直到最后一條記錄
sqlite3_coloum_xxx() : 獲取對(duì)應(yīng)類(lèi)型的內(nèi)容,iCol對(duì)應(yīng)的就是SQL語(yǔ)句中字段的順序,從0開(kāi)始。根據(jù)實(shí)際查詢(xún)字段的屬性,使用sqlite3_column_xxx取得對(duì)應(yīng)的內(nèi)容即可。
sqlite3_finalize() : 釋放stmt
/**
* 從表中讀取數(shù)據(jù)到數(shù)組中
*/
- (void)readData {
NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:1000];
char *sql = "select name, age from t_person;";
sqlite3_stmt *stmt;
NSInteger result = sqlite3_prepare_v2(_sqlite3, sql, -1, &stmt, NULL);
if (result == SQLITE_OK) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
char *name = (char *)sqlite3_column_text(stmt, 0);
NSInteger age = sqlite3_column_int(stmt, 1);
//創(chuàng)建對(duì)象
Person *person = [Person personWithName:[NSString stringWithUTF8String:name] Age:age];
[mArray addObject:person];
}
self.dataList = mArray;
}
sqlite3_finalize(stmt);
}
4.總結(jié)
總得來(lái)說(shuō),SQLite3的使用還是比較麻煩的,因?yàn)槎际切ヽ語(yǔ)言的函數(shù),理解起來(lái)有些困難。不過(guò)在一般開(kāi)發(fā)過(guò)程中,使用的都是第三方開(kāi)源庫(kù) FMDB,封裝了這些基本的c語(yǔ)言方法,使得我們?cè)谑褂脮r(shí)更加容易理解,提高開(kāi)發(fā)效率。
FMDB
1.簡(jiǎn)介
FMDB是iOS平臺(tái)的SQLite數(shù)據(jù)庫(kù)框架,它是以O(shè)C的方式封裝了SQLite的C語(yǔ)言API,它相對(duì)于cocoa自帶的C語(yǔ)言框架有如下的優(yōu)點(diǎn):
- 使用起來(lái)更加面向?qū)ο?,省去了很多麻煩、冗余的C語(yǔ)言代碼
- 對(duì)比蘋(píng)果自帶的Core Data框架,更加輕量級(jí)和靈活
- 提供了多線(xiàn)程安全的數(shù)據(jù)庫(kù)操作方法,有效地防止數(shù)據(jù)混亂
2.核心類(lèi)
FMDB有三個(gè)主要的類(lèi):
FMDatabase
一個(gè)FMDatabase對(duì)象就代表一個(gè)單獨(dú)的SQLite數(shù)據(jù)庫(kù),用來(lái)執(zhí)行SQL語(yǔ)句FMResultSet
使用FMDatabase執(zhí)行查詢(xún)后的結(jié)果集FMDatabaseQueue
用于在多線(xiàn)程中執(zhí)行多個(gè)查詢(xún)或更新,它是線(xiàn)程安全的
3.打開(kāi)數(shù)據(jù)庫(kù)
和c語(yǔ)言框架一樣,F(xiàn)MDB通過(guò)指定SQLite數(shù)據(jù)庫(kù)文件路徑來(lái)創(chuàng)建FMDatabase對(duì)象,但FMDB更加容易理解,使用起來(lái)更容易,使用之前一樣需要導(dǎo)入sqlite3.dylib。打開(kāi)數(shù)據(jù)庫(kù)方法如下:
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.db"];
FMDatabase *database = [FMDatabase databaseWithPath:path];
if (![database open]) {
NSLog(@"數(shù)據(jù)庫(kù)打開(kāi)失敗!");
}
值得注意的是,Path的值可以傳入以下三種情況:
具體文件路徑,如果不存在會(huì)自動(dòng)創(chuàng)建
空字符串@"",會(huì)在臨時(shí)目錄創(chuàng)建一個(gè)空的數(shù)據(jù)庫(kù),當(dāng)FMDatabase連接關(guān)閉時(shí),數(shù)據(jù)庫(kù)文件也被刪除
nil,會(huì)創(chuàng)建一個(gè)內(nèi)存中臨時(shí)數(shù)據(jù)庫(kù),當(dāng)FMDatabase連接關(guān)閉時(shí),數(shù)據(jù)庫(kù)會(huì)被銷(xiāo)毀
4.更新
在FMDB中,除查詢(xún)以外的所有操作,都稱(chēng)為“更新”, 如:create、drop、insert、update、delete等操作,使用executeUpdate:方法執(zhí)行更新:
//常用方法有以下3種:
- (BOOL)executeUpdate:(NSString*)sql, ...
- (BOOL)executeUpdateWithFormat:(NSString*)format, ...
- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments
//示例
[database executeUpdate:@"CREATE TABLE IF NOT EXISTS t_person(id integer primary key autoincrement, name text, age integer)"];
//或者
[database executeUpdate:@"INSERT INTO t_person(name, age) VALUES(?, ?)", @"Bourne", [NSNumber numberWithInt:42]];
5.查詢(xún)
- 查詢(xún)方法也有3種,使用起來(lái)相當(dāng)簡(jiǎn)單:
- (FMResultSet *)executeQuery:(NSString*)sql, ...
- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ...
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments
- 查詢(xún)示例:
//1.執(zhí)行查詢(xún)
FMResultSet *result = [database executeQuery:@"SELECT * FROM t_person"];
//2.遍歷結(jié)果集
while ([result next]) {
NSString *name = [result stringForColumn:@"name"];
int age = [result intForColumn:@"age"];
}
6.線(xiàn)程安全
在多個(gè)線(xiàn)程中同時(shí)使用一個(gè)FMDatabase實(shí)例是不明智的。不要讓多個(gè)線(xiàn)程分享同一個(gè)FMDatabase實(shí)例,它無(wú)法在多個(gè)線(xiàn)程中同時(shí)使用。 如果在多個(gè)線(xiàn)程中同時(shí)使用一個(gè)FMDatabase實(shí)例,會(huì)造成數(shù)據(jù)混亂等問(wèn)題。所以,請(qǐng)使用 FMDatabaseQueue,它是線(xiàn)程安全的。以下是使用方法:
- 創(chuàng)建隊(duì)列。
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
- 使用隊(duì)列
[queue inDatabase:^(FMDatabase *database) {
[database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_1", [NSNumber numberWithInt:1]];
[database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_2", [NSNumber numberWithInt:2]];
[database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_3", [NSNumber numberWithInt:3]];
FMResultSet *result = [database executeQuery:@"select * from t_person"];
while([result next]) {
}
}];
- 而且可以輕松地把簡(jiǎn)單任務(wù)包裝到事務(wù)里:
[queue inTransaction:^(FMDatabase *database, BOOL *rollback) {
[database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_1", [NSNumber numberWithInt:1]];
[database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_2", [NSNumber numberWithInt:2]];
[database executeUpdate:@"INSERT INTO t_person(name, age) VALUES (?, ?)", @"Bourne_3", [NSNumber numberWithInt:3]];
FMResultSet *result = [database executeQuery:@"select * from t_person"];
while([result next]) {
}
//回滾
*rollback = YES;
}];
FMDatabaseQueue 后臺(tái)會(huì)建立系列化的G-C-D隊(duì)列,并執(zhí)行你傳給G-C-D隊(duì)列的塊。這意味著 你從多線(xiàn)程同時(shí)調(diào)用調(diào)用方法,GDC也會(huì)按它接收的塊的順序來(lái)執(zhí)行。
CoreData
1.準(zhǔn)備工作
-
創(chuàng)建數(shù)據(jù)庫(kù)
新建文件,選擇CoreData -> DataModel 添加實(shí)體(表),Add Entity 給表中添加屬性,點(diǎn)擊Attributes下方的‘+’號(hào) -
創(chuàng)建模型文件
新建文件,選擇CoreData -> NSManaged Object subclass 根據(jù)提示,選擇實(shí)體 -
通過(guò)代碼,關(guān)聯(lián)數(shù)據(jù)庫(kù)和實(shí)體
- (void)viewDidLoad { [super viewDidLoad]; /* * 關(guān)聯(lián)的時(shí)候,如果本地沒(méi)有數(shù)據(jù)庫(kù)文件,Coreadata自己會(huì)創(chuàng)建 */ // 1. 上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 2. 上下文關(guān)連數(shù)據(jù)庫(kù) // 2.1 model模型文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 2.2 持久化存儲(chǔ)調(diào)度器 // 持久化,把數(shù)據(jù)保存到一個(gè)文件,而不是內(nèi)存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 2.3 設(shè)置CoreData數(shù)據(jù)庫(kù)的名字和路徑 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"]; [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil]; context.persistentStoreCoordinator = store; _context = context; }
2.CoreData的基本操作(CURD)
-
添加元素 - Create
-(IBAction)addEmployee{ // 創(chuàng)建一個(gè)員工對(duì)象 //Employee *emp = [[Employee alloc] init]; 不能用此方法創(chuàng)建 Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; emp.name = @"wangwu"; emp.height = @1.80; emp.birthday = [NSDate date]; // 直接保存數(shù)據(jù)庫(kù) NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } } -
讀取數(shù)據(jù) - Read
-(IBAction)readEmployee{ // 1.FetchRequest 獲取請(qǐng)求對(duì)象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.設(shè)置過(guò)濾條件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"]; request.predicate = pre; // 3.設(shè)置排序 // 身高的升序排序 NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heigtSort]; // 4.執(zhí)行請(qǐng)求 NSError *error = nil; NSArray *emps = [_context executeFetchRequest:request error:&error]; if (error) { NSLog(@"error"); } //NSLog(@"%@",emps); //遍歷員工 for (Employee *emp in emps) { NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday); } } -
修改數(shù)據(jù) - Update
-(IBAction)updateEmployee{ // 改變zhangsan的身高為2m // 1.查找到zhangsan // 1.1FectchRequest 抓取請(qǐng)求對(duì)象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 1.2設(shè)置過(guò)濾條件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"]; request.predicate = pre; // 1.3執(zhí)行請(qǐng)求 NSArray *emps = [_context executeFetchRequest:request error:nil]; // 2.更新身高 for (Employee *e in emps) { e.height = @2.0; } // 3.保存 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } } -
刪除數(shù)據(jù) - Delete
-(IBAction)deleteEmployee{ // 刪除 lisi // 1.查找lisi // 1.1FectchRequest 抓取請(qǐng)求對(duì)象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 1.2設(shè)置過(guò)濾條件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"lisi"]; request.predicate = pre; // 1.3執(zhí)行請(qǐng)求 NSArray *emps = [_context executeFetchRequest:request error:nil]; // 2.刪除 for (Employee *e in emps) { [_context deleteObject:e]; } // 3.保存 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } }
3.CoreData的表關(guān)聯(lián)
- 準(zhǔn)備工作
創(chuàng)建數(shù)據(jù)庫(kù)
新建文件,選擇CoreData -> DataModel
添加實(shí)體(表),Add Entity , 注意:這里根據(jù)關(guān)聯(lián)添加多個(gè)實(shí)體
給表中添加屬性,點(diǎn)擊Attributes下方的‘+’號(hào)
創(chuàng)建模型文件
新建文件,選擇CoreData -> NSManaged Object subclass
根據(jù)提示,選擇實(shí)體,注意:這里先選擇被關(guān)聯(lián)的實(shí)體,最后添加最上層的實(shí)體
- 通過(guò)代碼,關(guān)聯(lián)數(shù)據(jù)庫(kù)和實(shí)體
- (void)viewDidLoad {
[super viewDidLoad];
/*
* 關(guān)聯(lián)的時(shí)候,如果本地沒(méi)有數(shù)據(jù)庫(kù)文件,Coreadata自己會(huì)創(chuàng)建
*/
// 1. 上下文
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
// 2. 上下文關(guān)連數(shù)據(jù)庫(kù)
// 2.1 model模型文件
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
// 2.2 持久化存儲(chǔ)調(diào)度器
// 持久化,把數(shù)據(jù)保存到一個(gè)文件,而不是內(nèi)存
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
// 2.3 設(shè)置CoreData數(shù)據(jù)庫(kù)的名字和路徑
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *sqlitePath = [doc stringByAppendingPathComponent:@"company.sqlite"];
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
context.persistentStoreCoordinator = store;
_context = context;
}
- 基本操作
添加元素 - Create
-(IBAction)addEmployee{
// 1. 創(chuàng)建兩個(gè)部門(mén) ios android
//1.1 iOS部門(mén)
Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
iosDepart.name = @"ios";
iosDepart.departNo = @"0001";
iosDepart.createDate = [NSDate date];
//1.2 Android部門(mén)
Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context];
andrDepart.name = @"android";
andrDepart.departNo = @"0002";
andrDepart.createDate = [NSDate date];
//2. 創(chuàng)建兩個(gè)員工對(duì)象 zhangsan屬于ios部門(mén) lisi屬于android部門(mén)
//2.1 zhangsan
Employee *zhangsan = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
zhangsan.name = @"zhangsan";
zhangsan.height = @(1.90);
zhangsan.birthday = [NSDate date];
zhangsan.depart = iosDepart;
//2.2 lisi
Employee *lisi = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context];
lisi.name = @"lisi";
lisi.height = @2.0;
lisi.birthday = [NSDate date];
lisi.depart = andrDepart;
//3. 保存數(shù)據(jù)庫(kù)
NSError *error = nil;
[_context save:&error];
if (error) {
NSLog(@"%@",error);
}
}
- 讀取信息 - Read
-(IBAction)readEmployee{
// 讀取ios部門(mén)的員工
// 1.FectchRequest 抓取請(qǐng)求對(duì)象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 2.設(shè)置過(guò)濾條件
NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"android"];
request.predicate = pre;
// 4.執(zhí)行請(qǐng)求
NSError *error = nil;
NSArray *emps = [_context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"error");
}
//遍歷員工
for (Employee *emp in emps) {
NSLog(@"名字 %@ 部門(mén) %@",emp.name,emp.depart.name);
}
}
- 其他功能與前幾種類(lèi)似,這里不在贅述
4.CoreData的模糊查詢(xún)
- 準(zhǔn)備工作和上面類(lèi)似,主要是查詢(xún)方式不同
模糊查詢(xún)
-(IBAction)readEmployee{
// 1.FectchRequest 抓取請(qǐng)求對(duì)象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 2.設(shè)置排序
// 按照身高的升序排序
NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
request.sortDescriptors = @[heigtSort];
// 3.模糊查詢(xún)
// 3.1 名字以"wang"開(kāi)頭
// NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wangwu1"];
// request.predicate = pre;
// 名字以"1"結(jié)尾
// NSPredicate *pre = [NSPredicate predicateWithFormat:@"name ENDSWITH %@",@"1"];
// request.predicate = pre;
// 名字包含"wu1"
// NSPredicate *pre = [NSPredicate predicateWithFormat:@"name CONTAINS %@",@"wu1"];
// request.predicate = pre;
// like 匹配
NSPredicate *pre = [NSPredicate predicateWithFormat:@"name like %@",@"*wu12"];
request.predicate = pre;
// 4.執(zhí)行請(qǐng)求
NSError *error = nil;
NSArray *emps = [_context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"error");
}
//遍歷員工
for (Employee *emp in emps) {
NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
}
}
- 分頁(yè)查詢(xún)
-(void)pageSeacher{
// 1. FectchRequest 抓取請(qǐng)求對(duì)象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 2. 設(shè)置排序
// 身高的升序排序
NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO];
request.sortDescriptors = @[heigtSort];
// 3. 分頁(yè)查詢(xún)
// 總有共有15數(shù)據(jù)
// 每次獲取6條數(shù)據(jù)
// 第一頁(yè) 0,6
// 第二頁(yè) 6,6
// 第三頁(yè) 12,6 3條數(shù)據(jù)
// 3.1 分頁(yè)的起始索引
request.fetchOffset = 12;
// 3.2 分頁(yè)的條數(shù)
request.fetchLimit = 6;
// 4. 執(zhí)行請(qǐng)求
NSError *error = nil;
NSArray *emps = [_context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"error");
}
// 5. 遍歷員工
for (Employee *emp in emps) {
NSLog(@"名字 %@ 身高 %@ 生日 %@",emp.name,emp.height,emp.birthday);
}
}
5.多個(gè)數(shù)據(jù)庫(kù)的使用
注意:
創(chuàng)建多個(gè)數(shù)據(jù)庫(kù),即創(chuàng)建多個(gè)DataModel
一個(gè)數(shù)據(jù)庫(kù)對(duì)應(yīng)一個(gè)上下文
需要根據(jù)bundle名創(chuàng)建上下文
添加或讀取信息,需要根據(jù)不同的上下文,訪(fǎng)問(wèn)不同的實(shí)體關(guān)聯(lián)數(shù)據(jù)庫(kù)和實(shí)體
- (void)viewDidLoad {
[super viewDidLoad];
// 一個(gè)數(shù)據(jù)庫(kù)對(duì)應(yīng)一個(gè)上下文
_companyContext = [self setupContextWithModelName:@"Company"];
_weiboContext = [self setupContextWithModelName:@"Weibo"];
}
/**
* 根據(jù)模型文件,返回一個(gè)上下文
*/
-(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{
// 1. 上下文
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
// 2. 上下文關(guān)連數(shù)據(jù)庫(kù)
// 2.1 model模型文件
// 注意:如果使用下面的方法,如果 bundles為nil 會(huì)把bundles里面的所有模型文件的表放在一個(gè)數(shù)據(jù)庫(kù)
//NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
// 改為以下的方法獲?。? NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL];
// 2.2 持久化存儲(chǔ)調(diào)度器
// 持久化,把數(shù)據(jù)保存到一個(gè)文件,而不是內(nèi)存
NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
// 2.3 告訴Coredata數(shù)據(jù)庫(kù)的名字和路徑
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *sqliteName = [NSString stringWithFormat:@"%@.sqlite",modelName];
NSString *sqlitePath = [doc stringByAppendingPathComponent:sqliteName];
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
context.persistentStoreCoordinator = store;
// 3. 返回上下文
return context;
}
- 添加元素
-(IBAction)addEmployee{
// 1. 添加員工
Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_companyContext];
emp.name = @"zhagsan";
emp.height = @2.3;
emp.birthday = [NSDate date];
// 直接保存數(shù)據(jù)庫(kù)
[_companyContext save:nil];
// 2. 發(fā)微博
Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext];
status.text = @"發(fā)了一條微博!";
status.createDate = [NSDate date];
[_weiboContext save:nil];
}