我已经得到拉刷新工作很好,除了当表重新加载有一个秒延迟之前,表中的数据重新加载。
我是不是有什么小毛病?什么好主意吗?
viewDidLoad
:
override func viewDidLoad() {
super.viewDidLoad()
self.refreshControl?.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
self.getCloudKit()
}
handleRefresh
for Pull to Refresh:
func handleRefresh(refreshControl: UIRefreshControl) {
self.objects.removeAll()
self.getCloudKit()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
refreshControl.endRefreshing()
})
}
需要在两个地方的数据,所以创建了一个函数getCloudKit
:
func getCloudKit() {
publicData.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil { // There is no error
for play in results! {
let newPlay = Play()
newPlay.color = play["Color"] as! String
self.objects.append(newPlay)
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
} else {
print(error)
}
}
}
tableView
:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
let object = objects[indexPath.row]
if let label = cell.textLabel{
label.text = object.matchup
}
return cell
}
你应该这样做:
- 在
handleRefresh
函数中,添加一个bool来跟踪进程中的刷新操作-例如isLoading
。 - 在
getCloudKit
函数中,如果isLoading
为真,则在重新加载表视图之前调用endRefreshing
函数。 - 复位
isLoading
为false
- 重要-在刷新操作实例化之前不要删除模型数据。如果在获取数据时出现错误怎么办?只有在
getCloudKit
函数中得到响应后才删除它。 - 另外,作为旁注,如果我愿意的话,我会实现一个基于时间戳的方法,在这种方法中,我会将我的最后一个服务数据时间戳(从服务器获取最后更新的时间)传递到服务器,服务器端将返回给我完整的数据,只有在时间戳发生变化后,我才会期望他们告诉我没有变化。在这种情况下,我会简单地调用
endRefreshing
函数,不会重新加载表上的数据。相信我——这节省了很多,并提供了良好的最终用户体验,因为大多数时候数据没有变化!