我试图从核心数据中获取一个实体,具体取决于名为"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];
Run Code Online (Sandbox Code Playgroud)
最后一行抛出以下异常:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Vegetable subentitiesByName]: unrecognized selector sent to instance 0x6bbcdd0'
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
问题是你设置你的entity属性的方式NSFetchRequest.随着insertNewObjectForEntity:你实际上是在创建一个新的对象被插入到数据库后用[managedObjectContext save:&error];.
你想要做的是只为你的获取请求设置实体,而不是插入一个新对象:
NSEntityDescription *vegetable = [NSEntityDescription entityForName:@"Location"
inManagedObjectContext:self.managedObjectContext];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
500 次 |
| 最近记录: |