FetchedResultsController中没有任何部分

时间:2014-07-15 09:47:52

标签: ios core-data nsmanagedobject nsfetchedresultscontroller

我插入并保存托管对象:

  MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
  NSManagedObjectContext *context = [appDelegate managedObjectContext];

  MyCity* city = (MyCity*)[NSEntityDescription insertNewObjectForEntityForName:@"City" inManagedObjectContext:context];
  city.cityId = dict[@"id"];
  city.cityName = dict[@"name"];

  NSError *error;
  if (![context save:&error]) {
    NSLog(@"error: %@", [error localizedDescription]);
  }

我执行FRC请求:

  _fetchedResultsController = nil;
  if (![[self fetchedResultsController] performFetch:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
  }

这是我的FRC:

  if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
  }

  MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
  NSManagedObjectContext *context = [appDelegate managedObjectContext];

  NSEntityDescription *entity = [NSEntityDescription entityForName:@"City"
                                          inManagedObjectContext: context];
  NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"cityName" ascending:YES];
  NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, nil];

  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  [fetchRequest setEntity:entity];
  [fetchRequest setSortDescriptors:sortDescriptors];
  [fetchRequest setFetchBatchSize:10];

  NSFetchedResultsController *theFetchedResultsController =
  [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                    managedObjectContext:context
                                      sectionNameKeyPath: @"cityName"
                                               cacheName: @"cache"];
  [self setFetchedResultsController: theFetchedResultsController];
  _fetchedResultsController.delegate = self;

  return _fetchedResultsController;
}

performFetch之后,我看到了:

_fetchedResultsController.fetchedObjects //array of MyCity objects
_fetchedResultsController.sections //empty array

为什么_fetchedResultsController.sections为空?

当我不使用[context save:&error]时,我可以在_fetchedResultsController.sections中看到对象数组。

在我的代码中保存上下文有问题吗?我该如何保存nsmanagedobject和nsmanagedcontext?

1 个答案:

答案 0 :(得分:1)

可能dict为空,因此cityName为空且没有节标题。

此外,您应该持有对托管对象上下文的引用,而不是反复转到您的应用代理来获取它。

我还建议您在不使用fetchBatchSizecache:nil的情况下测试代码并稍后进行优化。

另请注意,通常的模式是在返回之前懒洋洋地创建FRC时进行提取。然后,您可以nil将其生成以获取,或者在现有实例上调用performFetch