IOS 开发中常常会用CoreData,CoreData实际上使用的是SQLLite。今天开始看了看CoreData的基本使用,记录一下学习过程与体会。数据库
在CoreData中有几个概念要清楚Model,Entity,,Attribute,Relationship。能够简单的用关系数据库的概念来解释:model为database,Entity对应一张表,Attribute为表中的字段,relationship为关系。xcode
明白概念之后来看看使用CoreData的具体步骤:dom
1,在项目中新建一个模型文件(Data Model),新建后项目里面会有一个*.xcdatamodeld文件生成。学习
2,根据需求在模型中添加Entity,也就是咱们理解的表。同时为Entity定义相应的Attribute。spa
3,确立Entity之间的关系,支持一对一和一对多关系code
4,为每一个Entity添加对应的NSManagedObject子类,实现数据存取操做orm
前3步均可以在可视化额界面下完成,第4须要本身写代码去实现。对象
在写代码以前须要了解CoreData里面几个重要对象:blog
NSManagedObject:经过CoreData取回的对象默认都是NSManagedObject,因此使用Core Data的Entity类都是继承自NSManagedObject。(能够在Model中新建Entity后由在xcode中新建NSManagedObject subclass由xcode自动生成对应子类)继承
NSManagedObjectContext:负责应用和数据库之间的工做
NSPersistantStoreCoordinator:能够指定文件并打开相应的SQLLite数据库。
NSFetchRequest:用来获取数据
NSEntityDesciption:表明Entity 对应的类
有了这些类基本就能够开始写本身的的代码了:
初始化须要用到的类实例:
- (id)init { self=[super init]; if(self != nil) { //读取model文件 model = [NSManagedObjectModel mergedModelFromBundles:nil]; NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model]; //设置SQLLite path NSString *path = [self noteArchivePath]; NSURL *storeURL = [NSURL fileURLWithPath:path]; NSError *error = nil; if([psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error] == nil ) { [NSException raise:@"Open failed" format:@"Reason: %@",[error localizedDescription]]; } //建立NSManagedObjectContext对象 context = [[NSManagedObjectContext alloc] init]; [context setPersistentStoreCoordinator:psc]; [context setUndoManager:nil]; } return self ; }
利用NSFetchRequest获取数据库中的数据:
- (NSUInteger)loadAllNotes { if(!allNotes) { NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *e = [[model entitiesByName] objectForKey:@"NoteItem"] ; [request setEntity:e]; NSError *error=nil; NSArray *result = [context executeFetchRequest:request error:&error] ; if(result == nil) { [NSException raise:@"Fetch failed" format:@"Reason: %@",[error localizedDescription]]; } allNotes = [[NSMutableArray alloc] initWithArray:result]; } return allNotes.count; }
对应Entity的类只能经过context来建立:
- (NoteItem *)createNoteItem { NoteItem *note = [NSEntityDescription insertNewObjectForEntityForName:@"NoteItem" inManagedObjectContext:context]; [allNotes addObject:note]; return note ; }
将数据保存到数据库中只要调用context中的对应方法就能够了:
- (BOOL)saveChanges { NSError *error = nil ; BOOL successful = [context save:&error]; if(!successful) { NSLog(@"Error saving %@",[error localizedDescription]); } return successful; }
删除:
- (void)removeNoteItem:(NoteItem *)note { [context deleteObject:(NSManagedObject *)note]; [allNotes removeObject:note]; }
这些我写一个小dome时候的代码,理解了上述用到的一些类就能够进行基本的存取操做了。
学习笔记,可能存在错误,仅供参考,欢迎指正。