IOS 開發中經常會用CoreData,CoreData實際上使用的是SQLLite。今天開始看了看CoreData的基本使用,記錄一下學習過程與體會。
在CoreData中有幾個概念要清楚Model,Entity,,Attribute,Relationship。可以簡單的用關系數據庫的概念來解釋:model為database,Entity對應一張表,Attribute為表中的字段,relationship為關系。
明白概念以后來看看使用CoreData的具體步驟:
1,在項目中新建一個模型文件(Data Model),新建后項目里面會有一個*.xcdatamodeld文件生成。
2,根據需求在模型中添加Entity,也就是我們理解的表。同時為Entity定義相應的Attribute。
3,確立Entity之間的關系,支持一對一和一對多關系
4,為每個Entity添加對應的NSManagedObject子類,實現數據存取操作
前3步都可以在可視化額界面下完成,第4需要自己寫代碼去實現。
在寫代碼之前需要了解CoreData里面幾個重要對象:
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時候的代碼,理解了上述用到的一些類就可以進行基本的存取操作了。
學習筆記,可能存在錯誤,僅供參考,歡迎指正。