使用core data
生活随笔
收集整理的這篇文章主要介紹了
使用core data
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
要使用core data,首先要得到
NSManagedObjectContext
之前看過斯坦福2011年冬的公開課程視頻,介紹過有2種方法得到
1.為通過UIManagedDocument
2.是在AppDelegate中定義@property
?
第一種方法較為容易,不過只支持IOS5或以上版本
先在要使用core data的UIViewController中定義UIManagedDocument的@property
然后通過以下代碼片段建立
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];url = [url URLByAppendingPathComponent:@"Albeum"];self.document=[[UIManagedDocument alloc] initWithFileURL:url];if([[NSFileManager defaultManager] fileExistsAtPath:[url path]]){[document openWithCompletionHandler:^(BOOL success) {if(success)[self documentIsReady];}];}else{[document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {if (success) {[self documentIsReady];}}];}
然后就可以在documentIsReady中寫要做的事情
?
以下是簡單的插入,然后使用NSFetchRequest查詢后輸出
-(void)documentIsReady{NSManagedObjectContext *context = document.managedObjectContext;AlbeumGroup *person=(AlbeumGroup *)[NSEntityDescription insertNewObjectForEntityForName:@"AlbeumGroup" inManagedObjectContext:context]; person.name=@"張三";NSError *error;if (![context save:&error]) { NSLog(@"error!"); }else { NSLog(@"save person ok."); }NSFetchRequest *request=[[NSFetchRequest alloc] init]; NSEntityDescription *entity=[NSEntityDescription entityForName:@"AlbeumGroup" inManagedObjectContext:context]; [request setEntity:entity];NSArray *results=[[context executeFetchRequest:request error:&error] copy];for (AlbeumGroup *p in results) { //NSLog(@">> p.id: %i p.name: %@",p.id,p.name); NSLog(@">>p.name: %@",p.name); } }轉(zhuǎn)載于:https://www.cnblogs.com/gachal/archive/2012/04/10/2440837.html
總結(jié)
以上是生活随笔為你收集整理的使用core data的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IE兼容低版本设置
- 下一篇: sql server 2008语言基础: