0

该代码在 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];

但在 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
    ...

如何解决此错误?

4

2 回答 2

6

fetchRequestWithEntityName:仅在 iOS 5 及更高版本中可用。

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

NSEntityDescription *fooBarEntity = [NSEntityDescription entityForName:@"FooBar" inManagedObjectContext:model.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:fooBarEntity];
于 2012-11-08T07:59:06.907 回答
0

问题是 NSFetchRequest 没有从中获取对象的上下文......您总是需要一个特定的上下文来获取 entityDescription 。在 ios5 中,entityDescription 的获取被很好地隐藏并延迟到你执行 fetch :) 因为它不是

标题是错误的顺便说一句。它说它对 ios4 有好处:

+ (NSFetchRequest*)fetchRequestWithEntityName:(NSString*)entityName NS_AVAILABLE(10_7, 4_0);

Id 提交了一个错误。无论如何@Martin R 是正确的:)

于 2012-11-08T09:10:15.217 回答