概念
Core Data是iOS5之后才出現(xiàn)的一個(gè)框架,它提供了對(duì)象-關(guān)系映射(ORM)的功能歧寺,即能夠?qū)C對(duì)象轉(zhuǎn)化成數(shù)據(jù)翅雏,保存在SQLite數(shù)據(jù)庫(kù)文件中,也能夠?qū)⒈4嬖跀?shù)據(jù)庫(kù)中的數(shù)據(jù)還原成OC對(duì)象梳码。在此數(shù)據(jù)操作期間隐圾,我們不需要編寫任何SQL語(yǔ)句,這個(gè)有點(diǎn)類似于著名的Hibernate持久化框架边翁,不過功能肯定是沒有Hibernate強(qiáng)大的.
- NSManagedObjectContext 操作數(shù)據(jù)庫(kù)的上下文
- NSManagedObjectModel 模型文件對(duì)象(相當(dāng)于數(shù)據(jù)庫(kù))
- NSPersistentStoreCoordinator 持久化調(diào)度器關(guān)聯(lián)上面的模型文件對(duì)象也是NSManagedObjectContext 必須設(shè)置的屬性.
- NSEntityDescription 數(shù)據(jù)實(shí)體 相當(dāng)于表(也就是我們的一個(gè)表對(duì)應(yīng)一個(gè)對(duì)象)
初始化操作
// 創(chuàng)建上下文對(duì)象
self.context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];
//設(shè)置 數(shù)據(jù)庫(kù)存儲(chǔ)路徑
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ù)庫(kù)路徑
[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ù)........