CoreData 練習

概念

Core Data是iOS5之后才出現(xiàn)的一個框架,它提供了對象-關(guān)系映射(ORM)的功能,即能夠?qū)C對象轉(zhuǎn)化成數(shù)據(jù),保存在SQLite數(shù)據(jù)庫文件中,也能夠?qū)⒈4嬖跀?shù)據(jù)庫中的數(shù)據(jù)還原成OC對象。在此數(shù)據(jù)操作期間,我們不需要編寫任何SQL語句,這個有點類似于著名的Hibernate持久化框架,不過功能肯定是沒有Hibernate強大的.

  • NSManagedObjectContext 操作數(shù)據(jù)庫的上下文
  • NSManagedObjectModel 模型文件對象(相當于數(shù)據(jù)庫)
  • NSPersistentStoreCoordinator 持久化調(diào)度器關(guān)聯(lián)上面的模型文件對象也是NSManagedObjectContext 必須設(shè)置的屬性.
  • NSEntityDescription 數(shù)據(jù)實體 相當于表(也就是我們的一個表對應(yīng)一個對象)

初始化操作

    // 創(chuàng)建上下文對象
self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];

//設(shè)置 數(shù)據(jù)庫存儲路徑
NSString * path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"student.sqlite"];
NSURL * fileUrl = [NSURL fileURLWithPath:path];

// 持久化調(diào)度器 關(guān)聯(lián)模型
NSPersistentStoreCoordinator * store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
NSError * error = nil;
//設(shè)置持久化調(diào)度器 數(shù)據(jù)庫路徑
[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:fileUrl options:nil error:&error];


//設(shè)置上下文 持久化調(diào)度器
self.context.persistentStoreCoordinator = store;

插入數(shù)據(jù)

Student * student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:self.context];

student.name =@"fdf";
student.age = @(10);

NSError * error = nil;
[self.context save:&error];

if (!error) {
    NSLog(@"success");
    
}else{
    NSLog(@"%@",error);
}

待續(xù)........

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容