我有UITableViewController
基本上是新闻Feed。我还实现了一个pull to refresh功能。但是有时候当我拉动刷新它会给我错误
'数组索引超出范围'。
我知道这意味着它试图得到的物品不存在,但你能告诉我为什么吗?这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
tableView.delegate = self
tableView.dataSource = self
}
和refresh()函数:
func refresh() {
//get username and match with userId
let getUser = PFUser.query()
getUser?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let users = objects {
//clean arrays and dictionaries so we don't get indexing error
self.messages.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
for object in users {
if let user = object as? PFUser {
//make userId = username
self.users[user.objectId!] = user.username!
}
}
}
})
let getPost = PFQuery(className: "Posts")
getPost.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
self.messages.removeAll(keepCapacity: true)
self.users.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
for object in objects {
self.messages.append(object["message"] as! String)
self.usernames.append(self.users[object["userId"] as! String]!)
self.tableView.reloadData()
}
}
}
self.refresher.endRefreshing()
}
答案 0 :(得分:0)
您似乎正在移除users
中的所有内容,然后尝试在getPost.findObjectsInBackgroundWithBlock
中访问它。
具体而言,在self.users.removeAll(keepCapacity: true)
之前调用self.usernames.append(self.users[object["userId"] as! String]!)
。
另外,请注意这两个查询执行 异步 。您无法保证在到达第二个查询的完成块时已填充users
。您很可能希望将您的两个查询重组为one compound query或嵌套它们(不推荐)。
最后,根据它的外观,您可能希望使用removeAll(keepCapacity: false)
而不是使用removeAll(keepCapacity: true)
保留容量。