【问题标题】:Core Data: keypath name not found in entity核心数据:实体中找不到键路径名称
【发布时间】:2011-04-12 15:24:28
【问题描述】:

这条消息让我崩溃了:

'NSInvalidArgumentException',原因:'keypath name not found in entity

显然我没有正确查询我的实体。

//fetching Data

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Viewer" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSString *attributeName = @"dF";

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",attributeName];
[fetchRequest setPredicate:predicate];

NSLog(@"predicate : %@",predicate);
NSError *error;
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
NSLog(@"items : %@",items);

[fetchRequest release];
    
//end of fetch

这是我的数据模型:

我想返回“dF”的值,不应该这样称呼它吗? :

NSString *attributeName = @"dF";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",attributeName];

【问题讨论】:

  • 您的谓词中的name 是什么?您的实体上没有属性name
  • 啊,这就是我感到困惑的地方。我想返回名称为 "dF" 的属性的值。

标签: objective-c swift core-data nsfetchrequest


【解决方案1】:

如果您想从dF 属性中获取值,则必须获取NSManagedObjects 的数组,然后使用[fetchedManagedObject valueForKey:@"dF"]; 来获取您的值。

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Viewer" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];

NSManagedObject *mo = [items objectAtIndex:0];  // assuming that array is not empty
id value = [mo valueForKey:@"dF"];

谓词用于获取满足您条件的NSManagedObjects 数组。例如。如果您的dF 是一个数字,您可以创建像“dF > 100”这样的谓词,那么您的获取请求将返回一个带有NSManagedObjects 的数组,该数组的dF 值> 100。但是如果您只想获取值,你不需要任何谓词。

【讨论】:

    【解决方案2】:

    我使用的是用字符串 key 初始化的 NSSortDescriptor:

    let fetchRequest = NSFetchRequest<SomeManagedObject>(entityName: "SomeManagedObject")
    let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]
    

    然后我更改了模型中name 属性的名称。重构了所有的属性名称,但没有捕捉到字符串类型的key: "name"

    Swift 的解决方案是使用NSSortDescriptor(keyPath: 代替,如果属性键路径发生变化,它将无法编译。

    NSSortDescriptor(keyPath: \SomeManagedObject.firstName, ascending: true)
    

    【讨论】:

      猜你喜欢
      • 2011-01-30
      • 2015-08-18
      • 2021-10-19
      • 2010-12-31
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      相关资源
      最近更新 更多