NSManagedObject *managedObject = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
NSString *name = @"JackChen";
// 通过KVC赋值
[managedObject setValue:name forKey:@"name"];
[managedObject setValue:@13 forKey:@"age"];
// 验证
NSError *error = NULL;
[managedObject validateValue:&name forKey:@"name" error:&error];
if (error) {
NSLog(@"%@",[error localizedDescription]);
}
// 添加数据
[self.managedObjectContext insertObject:managedObject];
Card *card = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Card class]) inManagedObjectContext:self.managedObjectContext];
card.cardID = @"1345678";
[self.managedObjectContext insertObject:card];
// 保存
[self saveContext];
// 查询
NSFetchRequest *request = [[NSFetchRequest alloc] init];
// 去哪个对象查询
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like ‘Jack*‘"];
[request setPredicate:predicate];
NSArray *arr = [self.managedObjectContext executeFetchRequest:request error:NULL];
for (NSManagedObject *obj in arr) {
NSLog(@"%@ --- %@",[obj valueForKey:@"name"], [obj valueForKey:@"age"]);
}