gpt4 book ai didi

iphone - 使用 NSFetchedResultsController 进行分页?

转载 作者:行者123 更新时间:2023-12-01 17:09:59 26 4
gpt4 key购买 nike

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

最佳答案

Swift 5 中,您可以这样做:

1 - 选择一个偏移量和一个限制:

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 您想要的方式,然后再次执行 fetch。

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

时清除缓存

关于iphone - 使用 NSFetchedResultsController 进行分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12631542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com