3

我想知道如何使用NSFetchedResultsController. 我希望每个页面包含 20 个条目,并有一个页面索引,可以让我在页面之间导航。

- (NSFetchedResultsController *)fetchedResultsController
{
    if (_fetchedResultsController) {
        return _fetchedResultsController;
    }


    [self getDataOptions];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Profile"];

     NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortByName]];

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

     NSError *error = nil;
     if (![self.fetchedResultsController performFetch:&error]) {
        NSLog(@" Error %@ %@", [error localizedDescription], error);
        abort();
     }

     return _fetchedResultsController;
}
4

2 回答 2

0

Swift 5中,您可以执行以下操作:

1 - 选择一个offset和一个limit

var offset: Int = 0
var limit: Int = 20

2 -NSFetchedRequest使用您的entityName(我的是“Product”)和NSFetchedResultsController缓存名称设置 ,例如:CACHENAME

lazy var fetchedResultsController: NSFetchedResultsController<Product> = {
  let fetchRequest = NSFetchRequest<Product>(entityName: "Product")

  // Configure Fetch Request
  fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
  fetchRequest.fetchOffset = self.offset
  fetchRequest.fetchLimit = self.limit

  let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataStack.shared.context, sectionNameKeyPath: nil, cacheName: "CACHENAME")
  fetchedResultsController.delegate = self
  return fetchedResultsController
}()

3 - 执行获取。

do {
  NSFetchedResultsController<Product>.deleteCache(withName: fetchedResultsController.cacheName)
  try fetchedResultsController.performFetch()
} catch {
  print("--->> Oops, perform fetch failed")
}

4 - 加载下一个信息,只需更改您想要的方式,然后再次执行获取offsetlimit

func loadNext() {
  let lastLimit = self.limit + 3
  self.limit = lastLimit

  fetchedResultsController.fetchRequest.fetchOffset = self.offset
  fetchedResultsController.fetchRequest.fetchLimit = self.lastLimit
  do {
    NSFetchedResultsController<Product>.deleteCache(withName: fetchedResultsController.cacheName)
    try fetchedResultsController.performFetch()
  } catch {
    print("--->> Oops, perform fetch failed")
  }
}

重要提示:每次调用时清除缓存performFetch

于 2019-08-21T03:25:47.207 回答
-1

结果控制器可以获取所有内容(因此它可以正确形成部分)......您看到数据的表格视图应该受到限制。

于 2013-04-10T13:05:02.110 回答