iOS數據持久化的方式

概論android

所謂的持久化,就是將數據保存到硬盤中,使得在應用程序或機器重啓後能夠繼續訪問以前保存的數據。在iOS開發中,有不少數據持久化的方案,接下來我將嘗試着介紹一下5種方案:ios

  • plist文件(屬性列表)git

  • preference(偏好設置)github

  • NSKeyedArchiver(歸檔)sql

  • SQLite 3數據庫

  • CoreData編程

沙盒數組

在介紹各類存儲方法以前,有必要說明如下沙盒機制。iOS程序默認狀況下只能訪問程序本身的目錄,這個目錄被稱爲「沙盒」。安全

1.結構多線程

既然沙盒就是一個文件夾,那就看看裏面有什麼吧。沙盒的目錄結構以下:

"應用程序包"
Documents
Library
    Caches
    Preferences
tmp

2.目錄特性

雖然沙盒中有這麼多文件夾,可是沒有文件夾都不盡相同,都有各自的特性。因此在選擇存放目錄時,必定要認真選擇適合的目錄。

"應用程序包": 這裏面存放的是應用程序的源文件,包括資源文件和可執行文件。

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

Documents: 最經常使用的目錄,iTunes同步該應用時會同步此文件夾中的內容,適合存儲重要數據。

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

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

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

Library/Preferences: iTunes同步該應用時會同步此文件夾中的內容,一般保存應用的設置信息。

tmp: iTunes不會同步此文件夾,系統可能在應用沒運行時就刪除該目錄下的文件,因此此目錄適合保存應用中的一些臨時文件,用完就刪除。

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

plist文件

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

能夠被序列化的類型只有以下幾種:

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.存儲

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

3.讀取

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

4.注意

  • 只有以上列出的類型才能使用plist文件存儲。

  • 存儲時使用writeToFile: atomically:方法。 其中atomically表示是否須要先寫入一個輔助文件,再把輔助文件拷貝到目標文件地址。這是更安全的寫入文件方法,通常都寫YES。

  • 讀取時使用arrayWithContentsOfFile:方法。

Preference

1.使用方法

//1.得到NSUserDefaults文件
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//2.向文件中寫入內容
[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.注意

  • 偏好設置是專門用來保存應用程序的配置信息的,通常不要在偏好設置中保存其餘數據。

  • 若是沒有調用synchronize方法,系統會根據I/O狀況不定時刻地保存到文件中。因此若是須要當即寫入文件的就必須調用synchronize方法。

  • 偏好設置會將全部數據保存到同一個文件中。即preference目錄下的一個以此應用包名來命名的plist文件。

NSKeyedArchiver

歸檔在iOS中是另外一種形式的序列化,只要遵循了NSCoding協議的對象均可以經過它實現序列化。因爲決大多數支持存儲數據的Foundation和Cocoa Touch類都遵循了NSCoding協議,所以,對於大多數類來講,歸檔相對而言仍是比較容易實現的。

1.遵循NSCoding協議

NSCoding協議聲明瞭兩個方法,這兩個方法都是必須實現的。一個用來講明如何將對象編碼到歸檔中,另外一個說明如何進行解檔來獲取一個新對象。

  • 遵循協議和設置屬性

  //1.遵循NSCoding協議 
  @interface Person : NSObject   //2.設置屬性
  @property (strong, nonatomic) UIImage *avatar;
  @property (copy, nonatomic) NSString *name;
  @property (assign, nonatomic) NSInteger age;
  @end
  • 實現協議方法

  //解檔
  - (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"];
  }
  • 特別注意

若是須要歸檔的類是某個自定義類的子類時,就須要在歸檔和解檔以前先實現父類的歸檔和解檔方法。即 [super encodeWithCoder:aCoder] 和 [super initWithCoder:aDecoder] 方法;

2.使用

須要把對象歸檔是調用NSKeyedArchiver的工廠方法 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];

須要從文件中解檔對象就調用NSKeyedUnarchiver的一個工廠方法 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.注意

  • 必須遵循並實現NSCoding協議

  • 保存文件的擴展名能夠任意指定

  • 繼承時必須先調用父類的歸檔解檔方法

SQLite3

以前的全部存儲方法,都是覆蓋存儲。若是想要增長一條數據就必須把整個文件讀出來,而後修改數據後再把整個內容覆蓋寫入文件。因此它們都不適合存儲大量的內容。

1.字段類型

表面上SQLite將數據分爲如下幾種類型:

  • integer : 整數

  • real : 實數(浮點數)

  • text : 文本字符串

  • blob : 二進制數據,好比文件,圖片之類的

實際上SQLite是無類型的。即無論你在創表時指定的字段類型是什麼,存儲是依然能夠存儲任意類型的數據。並且在創表時也能夠不指定字段類型。SQLite之因此什麼類型就是爲了良好的編程規範和方便開發人員交流,因此平時在使用時最好設置正確的字段類型!主鍵必須設置成integer

2. 準備工做

準備工做就是導入依賴庫啦,在iOS中要使用SQLite3,須要添加庫文件:libsqlite3.dylib並導入主頭文件,這是一個C語言的庫,因此直接使用SQLite3仍是比較麻煩的。

3.使用

  • 建立數據庫並打開

操做數據庫以前必須先指定數據庫文件和要操做的表,因此使用SQLite3,首先要打開數據庫文件,而後指定或建立一張表。

/**
*  打開數據庫並建立一個表
*/
- (void)openDatabase {
   //1.設置文件名
   NSString *filename = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.db"];
   //2.打開數據庫文件,若是沒有會自動建立一個文件
   NSInteger result = sqlite3_open(filename.UTF8String, &_sqlite3);
   if (result == SQLITE_OK) {
       NSLog(@"打開數據庫成功!");
       //3.建立一個數據庫表
       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(@"錯誤:%s", errmsg);
       } else {
           NSLog(@"創表成功!");
       }
   } else {
       NSLog(@"打開數據庫失敗!");
   }
}
  • 執行指令

使用 sqlite3_exec() 方法能夠執行任何SQL語句,好比創表、更新、插入和刪除操做。可是通常不用它執行查詢語句,由於它不會返回查詢到的數據。

/**
*  往表中插入1000條數據
*/
- (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(@"錯誤:%s", errmsg);
  }
}
NSLog(@"插入完畢!");
}
  • 查詢指令

前面說過通常不使用 sqlite3_exec() 方法查詢數據。由於查詢數據必需要得到查詢結果,因此查詢相對比較麻煩。示例代碼以下:

    • sqlite3_prepare_v2() : 檢查sql的合法性

    • sqlite3_step() : 逐行獲取查詢結果,不斷重複,直到最後一條記錄

    • sqlite3_coloum_xxx() : 獲取對應類型的內容,iCol對應的就是SQL語句中字段的順序,從0開始。根據實際查詢字段的屬性,使用sqlite3_column_xxx取得對應的內容便可。

    • sqlite3_finalize() : 釋放stmt

/**
*  從表中讀取數據到數組中
*/
- (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);
           //建立對象
           Person *person = [Person personWithName:[NSString stringWithUTF8String:name] Age:age];
           [mArray addObject:person];
       }
       self.dataList = mArray;
   }
   sqlite3_finalize(stmt);
}

4.總結

總得來講,SQLite3的使用仍是比較麻煩的,由於都是些c語言的函數,理解起來有些困難。不過在通常開發過程當中,使用的都是第三方開源庫 FMDB,封裝了這些基本的c語言方法,使得咱們在使用時更加容易理解,提升開發效率。

FMDB

1.簡介

FMDB是iOS平臺的SQLite數據庫框架,它是以OC的方式封裝了SQLite的C語言API,它相對於cocoa自帶的C語言框架有以下的優勢:

使用起來更加面向對象,省去了不少麻煩、冗餘的C語言代碼

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

提供了多線程安全的數據庫操做方法,有效地防止數據混亂

注:FMDB的gitHub地址

2.核心類

FMDB有三個主要的類:

  • FMDatabase

一個FMDatabase對象就表明一個單獨的SQLite數據庫,用來執行SQL語句

  • FMResultSet

使用FMDatabase執行查詢後的結果集

  • FMDatabaseQueue

用於在多線程中執行多個查詢或更新,它是線程安全的

3.打開數據庫

和c語言框架同樣,FMDB經過指定SQLite數據庫文件路徑來建立FMDatabase對象,但FMDB更加容易理解,使用起來更容易,使用以前同樣須要導入sqlite3.dylib。打開數據庫方法以下:

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.db"];
FMDatabase *database = [FMDatabase databaseWithPath:path];    
if (![database open]) {
    NSLog(@"數據庫打開失敗!");
}

值得注意的是,Path的值能夠傳入如下三種狀況:

  • 具體文件路徑,若是不存在會自動建立

  • 空字符串@"",會在臨時目錄建立一個空的數據庫,當FMDatabase鏈接關閉時,數據庫文件也被刪除

  • nil,會建立一個內存中臨時數據庫,當FMDatabase鏈接關閉時,數據庫會被銷燬

4.更新

在FMDB中,除查詢之外的全部操做,都稱爲「更新」, 如:create、drop、insert、update、delete等操做,使用executeUpdate:方法執行更新:

//經常使用方法有如下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.查詢

查詢方法也有3種,使用起來至關簡單:

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

查詢示例:

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

6.線程安全

在 多個線程中同時使用一個FMDatabase實例是不明智的。不要讓多個線程分享同一個FMDatabase實例,它沒法在多個線程中同時使用。 若是在多個線程中同時使用一個FMDatabase實例,會形成數據混亂等問題。因此,請使用 FMDatabaseQueue,它是線程安全的。如下是使用方法:

  • 建立隊列。

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

[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]) {   
         }    
}];

並且能夠輕鬆地把簡單任務包裝到事務裏:

[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 後臺會創建系列化的G-C-D隊列,並執行你傳給G-C-D隊列的塊。這意味着 你從多線程同時調用調用方法,GDC也會按它接收的塊的順序來執行。

 


.Core Data
Core Data本質上是使用SQLite保存數據,可是它不須要編寫任何SQL語句。


要使用Core Data,須要在Xcode中的數據模型編輯器中設計好各個實體以及定義好他們的屬性和關係。以後,經過操做這些對象,結合Core Data完成數據的持久化:


NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSError *error;
NSString *fieldName = [NSString stringWithFormat:@"test%d", i];
UITextField *theField = [self valueForKey:fieldName];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
//創 建描述語句,需求Line對象。相似於在數據庫中限定爲Line表。
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line"  inManagedObjectContext:context];
[request setEntity:entityDescription];
//建立限制性語句,相似於SQL語句中的 where lineNum = i
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(lineNum = %d)", i];
[request setPredicate:pred];
NSManagedObject *theLine = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil){
NSLog(@」There was an error!」);
// Do whatever error handling is appropriate
}
if ([objects count] > 0){    //若是符合條件的object存在,則取出
theLine = [objects objectAtIndex:0];
}
else {  //若是不存在,則插入一個新的.
theLine = [NSEntityDescription insertNewObjectForEntityForName:@"Line"
inManagedObjectContext:context];
[theLine setValue:[NSNumber numberWithInt:i] forKey:@」lineNum」];  //設置這個object的屬性,coredata會自動將其寫入sqlite
[theLine setValue:theField.text forKey:@"lineText"];
[request release];

}


下面是其取數據的過程:


Core_Data_PersistenceAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Line"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil)
{
NSLog(@」There was an error!」);
// Do whatever error handling is appropriate
}
//每個對象在CoreData中都表示爲一個NSManagedObject對象(相似於數據庫表中的每一行),他的屬性經過鍵/值 方式獲取
for (NSManagedObject *oneObject in objects)
{
NSNumber *lineNum = [oneObject valueForKey:@"lineNum"];
NSString *lineText = [oneObject valueForKey:@"lineText"];
}
[request release];

《轉載 http://www.jianshu.com/p/6e048f7c5812》

文/伯恩的遺產(簡書做者)
原文連接:http://www.jianshu.com/p/6e048f7c5812
著做權歸做者全部,轉載請聯繫做者得到受權,並標註「簡書做者」。

1、CoreData的簡單使用

準備工做

  • 建立數據庫

    1. 新建文件,選擇CoreData -> DataModel
    2. 添加實體(表),Add Entity
    3. 給表中添加屬性,點擊Attributes下方的‘+’
  • 建立模型文件

    1. 新建文件,選擇CoreData -> NSManaged Object subclass
    2. 根據提示,選擇實體
  • 經過代碼,關聯數據庫和實體

    - (void)viewDidLoad { [super viewDidLoad]; /* * 關聯的時候,若是本地沒有數據庫文件,Coreadata本身會建立 */ // 1. 上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 2. 上下文關連數據庫 // 2.1 model模型文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 2.2 持久化存儲調度器 // 持久化,把數據保存到一個文件,而不是內存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 2.3 設置CoreData數據庫的名字和路徑 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; }

CoreData的基本操做(CURD)

  • 添加元素 - Create

    -(IBAction)addEmployee{ // 建立一個員工對象 //Employee *emp = [[Employee alloc] init]; 不能用此方法建立 Employee *emp = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:_context]; emp.name = @"wangwu"; emp.height = @1.80; emp.birthday = [NSDate date]; // 直接保存數據庫 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } }
  • 讀取數據 - Read

    -(IBAction)readEmployee{ // 1.FetchRequest 獲取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.設置過濾條件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"]; request.predicate = pre; // 3.設置排序 // 身高的升序排序 NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heigtSort]; // 4.執行請求 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); } }
  • 修改數據 - Update

    -(IBAction)updateEmployee{ // 改變zhangsan的身高爲2m // 1.查找到zhangsan // 1.1FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 1.2設置過濾條件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"zhangsan"]; request.predicate = pre; // 1.3執行請求 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); } }
  • 刪除數據 - Delete

    -(IBAction)deleteEmployee{ // 刪除 lisi // 1.查找lisi // 1.1FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 1.2設置過濾條件 // 查找zhangsan NSPredicate *pre = [NSPredicate predicateWithFormat:@"name = %@", @"lisi"]; request.predicate = pre; // 1.3執行請求 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); } }

2、CoreData的表關聯

準備工做

  • 建立數據庫

    1. 新建文件,選擇CoreData -> DataModel
    2. 添加實體(表),Add Entity注意:這裏根據關聯添加多個實體
    3. 給表中添加屬性,點擊Attributes下方的‘+’
  • 建立模型文件

    1. 新建文件,選擇CoreData -> NSManaged Object subclass
    2. 根據提示,選擇實體,注意:這裏先選擇被關聯的實體,最後添加最上層的實體
  • 經過代碼,關聯數據庫和實體

    - (void)viewDidLoad { [super viewDidLoad]; /* * 關聯的時候,若是本地沒有數據庫文件,Coreadata本身會建立 */ // 1. 上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 2. 上下文關連數據庫 // 2.1 model模型文件 NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 2.2 持久化存儲調度器 // 持久化,把數據保存到一個文件,而不是內存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 2.3 設置CoreData數據庫的名字和路徑 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. 建立兩個部門 ios android //1.1 iOS部門 Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context]; iosDepart.name = @"ios"; iosDepart.departNo = @"0001"; iosDepart.createDate = [NSDate date]; //1.2 Android部門 Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:_context]; andrDepart.name = @"android"; andrDepart.departNo = @"0002"; andrDepart.createDate = [NSDate date]; //2. 建立兩個員工對象 zhangsan屬於ios部門 lisi屬於android部門 //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. 保存數據庫 NSError *error = nil; [_context save:&error]; if (error) { NSLog(@"%@",error); } }
  • 讀取信息 - Read

    -(IBAction)readEmployee{ // 讀取ios部門的員工 // 1.FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.設置過濾條件 NSPredicate *pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"android"]; request.predicate = pre; // 4.執行請求 NSError *error = nil; NSArray *emps = [_context executeFetchRequest:request error:&error]; if (error) { NSLog(@"error"); } //遍歷員工 for (Employee *emp in emps) { NSLog(@"名字 %@ 部門 %@",emp.name,emp.depart.name); } }
  • 其餘功能與前幾種相似,這裏不在贅述

3、CoreData的模糊查詢

準備工做和上面相似,主要是查詢方式不一樣

  • 模糊查詢

    -(IBAction)readEmployee{ // 1.FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2.設置排序 // 按照身高的升序排序 NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heigtSort]; // 3.模糊查詢 // 3.1 名字以"wang"開頭 // NSPredicate *pre = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@",@"wangwu1"]; // request.predicate = pre; // 名字以"1"結尾 // 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.執行請求 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); } }
  • 分頁查詢

    -(void)pageSeacher{ // 1. FectchRequest 抓取請求對象 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"]; // 2. 設置排序 // 身高的升序排序 NSSortDescriptor *heigtSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:NO]; request.sortDescriptors = @[heigtSort]; // 3. 分頁查詢 // 總有共有15數據 // 每次獲取6條數據 // 第一頁 0,6 // 第二頁 6,6 // 第三頁 12,6 3條數據 // 3.1 分頁的起始索引 request.fetchOffset = 12; // 3.2 分頁的條數 request.fetchLimit = 6; // 4. 執行請求 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); } }

4、多個數據庫的使用

注意:

建立多個數據庫,即建立多個DataModel
一個數據庫對應一個上下文
須要根據bundle名建立上下文
添加或讀取信息,須要根據不一樣的上下文,訪問不一樣的實體

  • 關聯數據庫和實體

    - (void)viewDidLoad { [super viewDidLoad]; // 一個數據庫對應一個上下文 _companyContext = [self setupContextWithModelName:@"Company"]; _weiboContext = [self setupContextWithModelName:@"Weibo"]; } /** * 根據模型文件,返回一個上下文 */ -(NSManagedObjectContext *)setupContextWithModelName:(NSString *)modelName{ // 1. 上下文 NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; // 2. 上下文關連數據庫 // 2.1 model模型文件 // 注意:若是使用下面的方法,若是 bundles爲nil 會把bundles裏面的全部模型文件的表放在一個數據庫 //NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil]; // 改成如下的方法獲取: NSURL *companyURL = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"]; NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:companyURL]; // 2.2 持久化存儲調度器 // 持久化,把數據保存到一個文件,而不是內存 NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; // 2.3 告訴Coredata數據庫的名字和路徑 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]; // 直接保存數據庫 [_companyContext save:nil]; // 2. 發微博 Status *status =[NSEntityDescription insertNewObjectForEntityForName:@"Status" inManagedObjectContext:_weiboContext]; status.text = @"發了一條微博!"; status.createDate = [NSDate date]; [_weiboContext save:nil]; }
相關文章
相關標籤/搜索