插入:
- (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];