我正在尝试从核心数据中获取实体,具体取决于名为“name”的属性。这是我的代码:
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *vegetable = [NSEntityDescription insertNewObjectForEntityForName:@"Vegetable" inManagedObjectContext:context];
// get the vegetable using name
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate =
[NSPredicate predicateWithFormat:@"name == %@", myGardenViewModel.vegetable.name];
[request setEntity:vegetable];
[request setPredicate:predicate];
NSError *error;
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:request error:&error];
最后一行抛出以下异常:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Vegetable subentitiesByName]: unrecognized selector sent to instance 0x6bbcdd0'
任何想法?
答案 0 :(得分:7)
问题在于您设置entity
的{{1}}属性的方式。使用NSFetchRequest
,您实际上是在稍后使用insertNewObjectForEntity:
创建要插入数据库的新对象。
您要做的只是为获取请求设置实体,而不是插入新对象:
[managedObjectContext save:&error];