5
- (void)fetchResult
{
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"Project" ascending:YES];

    [request setEntity:self.entityDescription];
    [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    self.fetchResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

    NSError *fetchError = nil;
    BOOL success = [self.fetchResultController performFetch:&fetchError];
    if (success) {
        NSLog(@"fetched!");
    }
    else {
    NSLog(@"fetch fail!");
    }
}

entityDescription 和上下文在 viewDidLoad 方法中设置,如下所示:

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
self.managedObjectContext = appDelegate.managedObjectContext;
self.entityDescription = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:self.managedObjectContext];

崩溃信息: *由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“在实体中找不到密钥路径项目”


有人可以帮忙吗?;)

4

5 回答 5

13

排序描述符中使用的键

[NSSortDescriptor sortDescriptorWithKey:@"Project" ascending:YES];

必须是您的核心数据实体的属性,而不是实体本身的名称。因此,您应该在排序描述符中替换@"Project"为 Project 实体的某些属性,例如@"name".

于 2013-05-02T08:04:04.660 回答
4

它与最初的问题无关,但与问题的标题高度相关。由于它是我为这个主题找到的唯一一个,它可能对其他人有用:

所以,我有“核心数据崩溃:'keypath Videos not found in entity ...' ”因为我在谓词中使用了字符串插值:

let projectName = "Videos"
let predicate = NSPredicate(format: "\(#keyPath(Scene.relatedProject.name)) == \(projectName)")

正确的方法是:

let projectName = "Videos"
let predicate = NSPredicate(format: "\(#keyPath(Scene.relatedProject.name)) == %@", projectName)

希望,这将节省一些小时(S)搞清楚发生了什么。

于 2019-11-08T16:25:58.537 回答
2

确保您对查询示例使用以下语法:

fetchRequest.predicate = NSPredicate(format: "username = %@ ", userName)

其中 username 是键,userName 是变量以保存示例中的任何名称。

于 2021-08-27T16:48:56.077 回答
0

设置缓存名称,如:

self.fetchResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"temp"];
于 2013-05-02T05:48:46.167 回答
0
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

[fetchRequest setPredicate:predicate];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Project"          inManagedObjectContext:context];

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"Column_Name"  ascending:YES];

[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

[fetchRequest setEntity:entity];

NSError *error = nil;
NSArray *arrTemp = [context executeFetchRequest:fetchRequest error:&error];

if([arrTemp count]>0){
   NSLog(@"%@",arrTemp);
}
于 2013-05-02T13:13:06.437 回答