概念
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ù)........