數據持久化———CoreData

1.Core data 使用面向對象的方式操作數據,用來解決與對象生命週期管理,對象關係圖管理和持久化等方面相關的問題

2.使用core Data 的版本偏移問題

  • 對數據模型進行版本管理

  • 數據遷移:不同版本數據模型之間進行轉換的機制

  • 輕量級遷移

  • 標準遷移

  • 輕量遷移和標準遷移的區別:

    CoreData支持兩種不同類型的遷移。輕量遷移和標準遷移。

    如果你添加或移除了實體中的屬性,或者在數據模型中新增或刪除實體,輕量遷移即可,但如果將一個實體切分成兩個不同的實體,或者將某個屬性從一個實體中移動到另一個實體,輕量遷移無效,需要用標準遷移。

1. 關於數據模型

  • 數據模型會被編譯


    •   .xcdatamodel文件會編譯成一種新的文件,其擴展名爲.mom,它表示Managed Object Model。

  • 數據模型可以擁有多個版本

  • 創建新數據模型


    •   選中模型--》點擊Editor菜單--》選擇Add Model Version

  • 2. 遷移


    •   用於相對簡單的數據模型修改。(如簡單的添加或移除實體中的屬性,或添加移除實體)。


    • // 在設置持久化存儲助手的時候進行一些修改
      if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]){}
      // 替換爲
      NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption:@YES,NSInferMappingModelAutomaticallyOption:@YES};
      if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]){}


    • 輕量遷移


core Data 使用的步驟

- (void)viewDidLoad {
    [
super viewDidLoad];
   
// Do any additional setup after loading the view, typically from a nib.
   
    [
self openDataBase];
   
   
//當數據庫有數據保存時系統就會發出通知
    [[
NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notificationAction:) name:NSManagedObjectContextDidSaveNotification object:nil];
}

- (
void)notificationAction:(NSNotification *)notification
{
   
NSManagedObjectContext *savaContext = notification.object;
   
if (savaContext == context || savaContext.persistentStoreCoordinator != context.persistentStoreCoordinator) {
       
return;
    }
   
//當要保存的NSManagedObjectContext對象與自身對象不同時,回到主線程對數據進行合併
   
dispatch_async(dispatch_get_main_queue(), ^{
       
//回到主線程對數據進行合併
        [
context mergeChangesFromContextDidSaveNotification:notification];
    });
   
   
}
- (
void)openDataBase
{
   
//1.加載數據庫模型文件
   
NSURL *url = [[NSBundle mainBundle]URLForResource:@"DBModel" withExtension:@"momd"];
   
//MOM
   
NSManagedObjectModel *dataModel = [[NSManagedObjectModel alloc]initWithContentsOfURL:url];
   
//2.打開數據庫
   
store = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:dataModel];
   
   
//定義數據庫文件的路徑
   
NSString *filePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/coreData.sqlite"];
   
NSURL *dbUrl = [NSURL fileURLWithPath:filePath];
   
NSError *error = nil;
    [
store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:dbUrl options:nil error:&error];
   
   
if (error) {
       
NSLog(@"打開數據庫失敗-%@",error);
    }
else{
       
NSLog(@"打開數據庫成功");
    }
   
   
//3.對數據庫進行操作
   
context = [[NSManagedObjectContext alloc]init];
   
context.persistentStoreCoordinator = store;
   
   
}
- (
IBAction)addData:(id)sender {
   
   
for (int i = 0; i < 100; i ++) {
       
User *user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context];
        user.
userID = [@(i) stringValue];
        user.
name = [NSString stringWithFormat:@"name--%d",i];
        user.
age = @(i);
    }
   
   
if ([context save:nil]) {
       
NSLog(@"數據添加成功");
    }
else{
       
NSLog(@"數據添加失敗");
    }
   
}

//同步查詢
- (
IBAction)sysQuery:(id)sender {
   
   
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
   
NSArray *array = [context executeFetchRequest:request error:nil];
   
for (User *user in array) {
       
NSLog(@"name:%@   userid:%@   age:%@  ",user.name,user.userID,user.age);
    }
   
}
//異步查詢
- (
IBAction)asysQuery:(id)sender {
   
   
   
//創建異步線程隊列,將數據查詢放入到異步線程隊列中
   
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [queue
addOperationWithBlock:^{
       
//注意:要將異步線程中的執行代碼放入到自動釋放池中
       
@autoreleasepool {
           
//多線程
           
//1.創建MOC
           
//在多線程中,MOC要重新創建,PSC 可以用同一個
           
NSManagedObjectContext *contxt = [[NSManagedObjectContext alloc]init];
           
           
//2.創建PSC
            contxt.
persistentStoreCoordinator = store;
           
           
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
           
NSArray *array = [contxt executeFetchRequest:request error:nil];
           
for (User *user in array) {
                user.
age = @([user.age intValue] + 10000);
               
NSLog(@"name:%@   userid:%@   age:%@  ",user.name,user.userID,user.age);
            }
           
           
//保存
            [contxt
save:nil];
        }
       
    }];
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章