core-data - 使用属性搜索实体时的核心数据 SubEntitiesByName

标签 core-data ios5

我试图根据名为“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'

有任何想法吗?

最佳答案

问题在于您设置 entity 的方式您的属性(property)NSFetchRequest .与 insertNewObjectForEntity:您实际上是在创建一个新对象,稍后将使用 [managedObjectContext save:&error]; 将其插入到数据库中。 .

您想要做的只是为您的 fetch 请求设置实体,而不是插入一个新对象:

NSEntityDescription *vegetable = [NSEntityDescription entityForName:@"Location" 
   inManagedObjectContext:self.managedObjectContext];

关于core-data - 使用属性搜索实体时的核心数据 SubEntitiesByName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8527172/

相关文章:

objective-c - 从您的应用程序内部调用 map 获取方向 - iOS 5 iOS 6

iphone - 执行多线程的正确方法

iphone - iOS TableView 加载数据很慢

ios - 替代 iOS 10.0 核心数据中的 NSPersistentStoreUbiquitousContentNameKey 键

iphone - NSPredicate 不适用于 double 值 (%f)?

iphone - 在应用程序中传送预填充的 SQLite 数据库。启动时数据库的路径

ios - 所有 Core Data 属性都变为 nil

iphone - 如何在ViewController中初始化实例变量和属性

ios - 核心数据 NSPersistentStoreCoordinator 的 +metadataForPersistentStoreOfType :URL:error: sometimes returns nil

iphone - 添加 TabBar 元素