使用NSFetchedResultsController分页?

时间:2012-09-27 23:28:53

标签: iphone ios cocoa-touch ipad nsfetchedresultscontroller

我想知道如何使用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;
}

2 个答案:

答案 0 :(得分: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

时,清除缓存

答案 1 :(得分:-1)

结果控制器可以获取所有(因此它可以正确地形成部分)...你的tableview,你看到的数据应该被限制。