我有一个自定义控件,其数据源类似于UITableView的工作方式。我还添加了reloadData函数来加载新数据。
我希望每个运行循环调用一次重载数据实现,以避免多次重载相同的数据。
这是我当前的实现:
func reloadData(){
guard reloadDataScheduled == false else{
return
}
self.reloadDataScheduled = true
NSRunLoop.currentRunLoop().performSelector("innerReloadData", target: self, argument: nil, order: 0, modes: [NSDefaultRunLoopMode])
}
innerReloadData是实际执行加载的 private 函数,并将reloadDataScheduled设置为false。
这似乎在大多数情况下都有效,但是在其他情况下,它似乎会延迟2秒以上,这不是我想要的。
我需要深入了解运行循环的延迟,或者需要有关如何实现这种实现方式的任何建议。
最佳答案
在这种情况下,我通常使用以下代码。
- (void)setNeedsReloadData
{
// cancel all previous schedules
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadData) object:nil];
// below codes schedule "immediately run after current fetching on runloop"
[self performSelector:@selector(reloadData) withObject:nil afterDelay:0];
}
- (void)reloadData
{
// cancel the others schedules
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(reloadData) object:nil];
// Reload Data
...
}
您可以随时随地调用
-[XXX setNeedsReloadData]
。reloadData
将在runloop上每次获取运行一次。ps。在SWIFT中
Swift 1.1之前的
[NSObject performSelector: withObject: afterDelay:]
。 关于ios - 如何实现类似UITableView reloadData的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36000768/