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時候的代碼,理解了上述用到的一些類就能夠進行基本的存取操做了。
學習筆記,可能存在錯誤,僅供參考,歡迎指正。