如何实现类似 UITableView reloadData 的东西
How to implement something like UITableView reloadData
我有一个自定义控件,其数据源类似于 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 是一个私有函数,它实际执行加载,并将 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
将 运行 每次在 运行 循环中获取一次。
ps。在 SWIFT
- 在 swift 1.1 -
[NSObject performSelector: withObject: afterDelay:]
之前被阻止。
- 在 swift 2.0 之后 - 现在允许。
我有一个自定义控件,其数据源类似于 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 是一个私有函数,它实际执行加载,并将 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
将 运行 每次在 运行 循环中获取一次。
ps。在 SWIFT
- 在 swift 1.1 -
[NSObject performSelector: withObject: afterDelay:]
之前被阻止。 - 在 swift 2.0 之后 - 现在允许。