5

我因这条消息而崩溃:

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

Obvisouly 我没有正确查询我的实体。

//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];
4

2 回答 2

7

如果您想从您的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。但是如果您只想获取值,则不需要任何谓词。

于 2010-09-15T12:33:00.727 回答
0

我使用的是用 String 初始化的 NSSortDescriptor key

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

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

Swift 的解决方案是改为使用NSSortDescriptor(keyPath:,如果属性键路径发生更改,将无法编译。

NSSortDescriptor(keyPath: \SomeManagedObject.firstName, ascending: true)
于 2021-11-11T20:29:33.073 回答