Core Data: Keypath “objectID” not found in entity

天大地大妈咪最大 提交于 2019-12-19 13:12:47

问题


I'm using NSFetchedResultsController with a predicate to load a list of Documents in my application. I want to load all the Documents except the currently active one.

I am using Rentzsch's MOGenerator to create a _Document class and then I put all my custom code in the Document subclass. _Document generates an objectID property with type DocumentID.

In the class that creates the controller, I set the controller's currentDocID property:

controller.currentDocID = self.document.objectID;

In the controller itself, I lazy load the fetchedResultsController like this:

- (NSFetchedResultsController *)fetchedResultsController {
    if (fetchedResultsController != nil) {
        return fetchedResultsController;
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Document" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(objectID != %@)", self.currentDocID];
    [fetchRequest setPredicate:predicate];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dateModified" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    [aFetchedResultsController release];
    [sortDescriptor release];
    [sortDescriptors release];

    return fetchedResultsController;
}

When the fetchedResultsController loads, my app crashes with an unhandled exception:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath objectID not found in entity <NSSQLEntity Document id=1>'

It's my understanding that all NSManagedObjects have an objectID, whether temporary or permanent. Is this not the case? Any thoughts?


回答1:


Change your predicate to read

[NSPredicate predicateWithFormat:@"self != %@", [self currentDoc]]

Where currentDoc is a reference to the instance of the NSManagedObject that represents the current document.

Core Data will do the equality check internally.



来源:https://stackoverflow.com/questions/2493108/core-data-keypath-objectid-not-found-in-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!