1

我試圖使用一個iPhone應用程序中的核心數據,但是當我啓動應用程序我得到這個錯誤:NSFetchedResultsController的一個實例都需要一個非空fetchRequest和managedObjectContext

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'An instance of NSFetchedResultsController requires a non-nil fetchRequest and managedObjectContext' 

的代碼是這樣的:

#import "CocktailController.h" 

@implementation CocktailController 

@synthesize tableView; 
@synthesize cocktailDetailController; 
@synthesize fetchedResultsController=fetchedResultsController_, managedObjectContext=managedObjectContext_; 

#pragma mark Instance Methods 

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { 

    NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
    cell.textLabel.text = [[managedObject valueForKey:@"name"] description]; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    self.title = @"Cocktails"; 
} 

- (void)didReceiveMemoryWarning { 
    // Releases the view if it doesn't have a superview. 
    [super didReceiveMemoryWarning]; 

    // Release any cached data, images, etc that aren't in use. 
} 

- (void)dealloc { 
    [fetchedResultsController_ release]; 
    [managedObjectContext_ release]; 
    [tableView release]; 
    [cocktails release]; 
    [super dealloc]; 
} 

#pragma mark UITableViewDataSource Methods 

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:@"cell"]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"cell"] autorelease]; 
    } 
    Cocktail *cocktail = [cocktails objectAtIndex:indexPath.row]; 

    cell.textLabel.text = cocktail.name; 
    return cell; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return [[self.fetchedResultsController sections] count]; 
} 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 
    return [sectionInfo numberOfObjects]; 
} 

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    [tv deselectRowAtIndexPath:indexPath animated:YES]; 
} 

#pragma mark - 
#pragma mark Fetched results controller 

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

    /* 
    Set up the fetched results controller. 
    */ 
    // Create the fetch request for the entity. 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    // Edit the entity name as appropriate. 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Cocktail" inManagedObjectContext:managedObjectContext]; 
    [fetchRequest setEntity:entity]; 

    // Set the batch size to a suitable number. 
    [fetchRequest setFetchBatchSize:20]; 

    // Edit the sort key as appropriate. 
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO]; 
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; 

    [fetchRequest setSortDescriptors:sortDescriptors]; 

    // Edit the section name key path and cache name if appropriate. 
    // nil for section name key path means "no sections". 
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"]; 
    aFetchedResultsController.delegate = self; 
    self.fetchedResultsController = aFetchedResultsController; 

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

    NSError *error = nil; 
    if (![fetchedResultsController_ performFetch:&error]) { 
     /* 
     Replace this implementation with code to handle the error appropriately. 

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 
     */ 
     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    } 

    return fetchedResultsController_; 
}  


#pragma mark - 
#pragma mark Fetched results controller delegate 


- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { 
    [self.tableView beginUpdates]; 
} 


- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo 
      atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { 

    switch(type) { 
     case NSFetchedResultsChangeInsert: 
      [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeDelete: 
      [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
    } 
} 


- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject 
     atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type 
     newIndexPath:(NSIndexPath *)newIndexPath { 

    UITableView *tableView = self.tableView; 

    switch(type) { 

     case NSFetchedResultsChangeInsert: 
      [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeDelete: 
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeUpdate: 
      [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; 
      break; 

     case NSFetchedResultsChangeMove: 
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
    } 
} 


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { 
    [self.tableView endUpdates]; 
} 

它是一個應用程序的TabBar內部(並且具有導航控制器)

由於

@end 

回答

4

您確定要正確設置託管對象上下文嗎? 從我在那裏可以看到的情況來看,正在正確創建提取請求,但是您不會在該類中設置上下文。在顯示視圖之前,您是否在另一個課程中設置了上下文?

通常我把上下文的應用程序委託,然後設置類的背景下viewDidLoad中,或fetchedResultsController像這樣:

AppDelegate *delegate = [[NSApplication sharedApplication] delegate]; 
self.managedObjectContext = delegate.managedObjectContext; 

希望這有助於!祝你好運!

+0

非常感謝你:)它工作正常:) – patrick 2010-10-12 11:20:07

3

不需要在要使用managedObjectContext的任何控制器中包含AppDelegate依賴關係的方法就是在應用程序完成啓動時將對象傳遞給控制器​​。

在AppDelegate.m,方法didFinishLaunchingWithOptions做到以下幾點:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController; 
    UINavigationController *navigationController = (UINavigationController *)[[tabBarController viewControllers] objectAtIndex:0]; 
    YourController *controller = (YourController *)[[navigationController viewControllers] objectAtIndex:0]; 
    controller.managedObjectContext = self.managedObjectContext; 

    return YES; 
} 

請確保您有您的控制器上的財產managedObjectContext。

1

其後期的答覆,但我根據我的代碼最後一天,所以不得不完全一樣的問題:

NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; 
[fetchRequest setSortDescriptors:sortDescriptors]; 

我下面的行之後把上面的代碼行:

_fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"author" cacheName:nil]; 

所以構建出現了錯誤。所以我明白,在將獲取請求分配給Fetched Results Controller之前,必須將Sort描述符設置爲獲取請求。

把它放在正確的地方解決了我的問題。希望這可以幫助任何面對這種情況的人。

相關問題