使用core data

要使用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); 
    }
}



posted @ 2012-04-10 16:43  扎克  阅读(451)  评论(0编辑  收藏  举报