码迷,mamicode.com
首页 > 其他好文 > 详细

CoreData

时间:2015-03-19 10:00:23      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

插入:

- (void)insertCoreData2
{
    NSManagedObjectContext *context = [self managedObjectContext];
    Orange *orange = [NSEntityDescription insertNewObjectForEntityForName:@"Orange" inManagedObjectContext:context];
    
    orange.color = @"org";
    NSError *error;
    BOOL b = [context save:&error];
    NSLog(@"%@",b?@"YES":@"NO");
}

 

 查询:

- (void)getByQuery
{
    NSManagedObjectContext *context = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Orange" inManagedObjectContext:context]];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"color like[cd]‘red‘"];
    [fetchRequest setPredicate:predicate];
    [fetchRequest setFetchBatchSize:5];
    [fetchRequest setFetchOffset:0];
    [fetchRequest setFetchLimit:5];
    NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@"color" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDesc, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];
    NSError *error;
    NSArray *fetchedItems = [context executeFetchRequest:fetchRequest error:&error];
    if (fetchRequest == nil) {
        NSLog(@"fetch request resulted in an error: %@,%@ ", error, [error userInfo]);
    }
    for (Orange *orange in fetchedItems) {
        NSLog(@"%@", orange.color);
    }
}

 

 更新:

 NSFetchRequest* request=[[NSFetchRequest alloc] init];  
    NSEntityDescription* user=[NSEntityDescription entityForName:@"User" inManagedObjectContext:_myAppDelegate.managedObjectContext];  
    [request setEntity:user];  
    //查询条件  
    NSPredicate* predicate=[NSPredicate predicateWithFormat:@"name==%@",@"chen"];  
    [request setPredicate:predicate];  
    NSError* error=nil;  
    NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];  
    if (mutableFetchResult==nil) {  
        NSLog(@"Error:%@",error);  
    }  
    NSLog(@"The count of entry: %i",[mutableFetchResult count]);  
    //更新age后要进行保存,否则没更新  
    for (User* user in mutableFetchResult) {  
        [user setAge:[NSNumber numberWithInt:12]];  
          
    }  
    [_myAppDelegate.managedObjectContext save:&error];  
    [mutableFetchResult release];  
    [request release]; 

 

CoreData

标签:

原文地址:http://www.cnblogs.com/apem/p/4349524.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!