CoreData 手動自動 建立context(上下文)

weixin_34321977發表於2016-07-12

方法一:自定義context

 上下文關連資料庫,model模型檔案
       NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
        持久化,把資料儲存到一個檔案,而不是記憶體
        NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        
         告訴Coredata資料庫的名字和路徑
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        
       NSString *sqlitePath = [doc stringByAppendingPathComponent:@"YQHItList.sqlite"];
        [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:nil];
        
        _context.persistentStoreCoordinator = store;
    

方法二:系統自動生成(在AppDelegate內部)然後其他類裡面進行呼叫:

   怎麼 取到context?
    AppDelegate*appDelegate=[[UIApplication sharedApplication]delegate];
    self.context=appDelegate.managedObjectContext;
因為下面程式也要使用到
    

資料儲存

什麼時候進行資料儲存,要根據你自己的程式來
//確認按鈕
    UIAlertAction *okAction=[UIAlertAction actionWithTitle:@"確認新增" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
          //例項化實體類
        YQPerson *person =[NSEntityDescription insertNewObjectForEntityForName:@"YQPerson" inManagedObjectContext:_context ];
//    給實體類的name賦值
        person.name=[alert.textFields[0] text];
        NSError*error=nil;
        [_context save:&error];
        NSLog(@"%@",person.name);
        
        
        //判斷如果出錯
        if (error) {
            NSLog(@"%@",person.name);
        }
        //將資料降入可變陣列
        [_mutable addObject:person.name];
        
        //重新整理資料(全域性重新整理)
        [self.tableView reloadData];
    
    }];

這裡我是在點選一個按鈕彈出alert框內部可以輸入text,在我點選確定按鈕的時候進行資料儲存

資料查詢(從你儲存的裡面取出來,下一次執行程式時還能顯示在螢幕上)

請求
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"YQPerson"];
       
        NSError *error = nil;
        從coredata中查詢出資料 存入一個陣列
        NSArray *ps= [_context executeFetchRequest:request error:&error];
        ;
        NSLog(@"%@",[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"YQHItList.sqlite"]);
        NSLog(@"%@",ps);
        if (error) {
            NSLog(@"error");
        }
        
        _mutable = [NSMutableArray array];
注意二:這一步不能少,少了之後系統不能識別我們這個是什麼東西 ,必須借用一個新物件然後等價於我們這個陣列才可以進行下一步操作
    [_mutable removeAllObjects];
    快速查詢對應name 存入可變陣列用於介面顯示
        for (YQPerson *p in ps) {
            [_mutable addObject:p.name];
        }
        NSLog(@"%@",_mutable);

方法二怎麼自動生成的步驟就不提了 ,可以去其他帖子看一下,我這裡只是簡單做一下筆記,因為我之前做這個簡單的專案的時候遇到了比較難發現的問題: 能存進去但是取不出來

能存context save: 是成功的,但是fetch的時候就不成功了...

1.viewDidLoad中我[self fetch];操作放在了context獲取操作之前了 ,這樣就不能根據context 來獲取你儲存的東西了 記住

相關文章