如何修复'NSObjectInaccessibleException'获取请求在NSManagedObjectContext使用之前无法响应-entity

fre*_*ler 0 iphone cocoa-touch core-data objective-c ios

代码在iOS5 +中运行良好:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"FooBar"];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"ident"
                                                                                 ascending:NO
                                                                                  selector:@selector(compare:)]];
request.predicate = [NSPredicate predicateWithFormat:@"xxx = %@", @"yyy"];

self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                    managedObjectContext:model.managedObjectContext
                                                                      sectionNameKeyPath:nil
                                                                               cacheName:nil];
Run Code Online (Sandbox Code Playgroud)

但在iOS 4中,我收到以下错误:

'NSObjectInaccessibleException', reason: 'This fetch request (0x70d4700) 
was created with a string name (FooBar), and cannot respond to -entity 
until used by an NSManagedObjectContext'

2012-11-08 12:12:18.093 hello[1566:11d03] *** Terminating app due to uncaught
exception 'NSObjectInaccessibleException', reason: 'This fetch request 
(0x70d4700) was created with a string name (FooBar), and cannot respond 
to -entity until used by an NSManagedObjectContext'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x012405a9 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x0104a313 objc_exception_throw + 44
    2   CoreData                            0x000be68f -[NSFetchRequest entity] + 159
    3   CoreData                            0x0019f7fb -[NSFetchedResultsController initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName:] + 763
    ...
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个错误?

Mar*_*n R 6

fetchRequestWithEntityName: 仅适用于iOS 5及更高版本.

在iOS 4上,您必须创建NSEntityDescription第一个:

NSEntityDescription *fooBarEntity = [NSEntityDescription entityForName:@"FooBar" inManagedObjectContext:model.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:fooBarEntity];
Run Code Online (Sandbox Code Playgroud)