Swift UITableView索引超出范围错误

时间:2017-10-30 20:35:31

标签: ios swift uitableview

我在Swift中运行Firebase应用。在这里,我正在寻找关注者和关注用户。在用户刚刚注册的情况下,应用程序崩溃,因为可能没有关注者/关注用户。我已经尝试了所有我能想到的处理错误的东西,并且都没有帮助。我的问题是: 1.我怎样才能避免这次崩溃? 2.我有什么方法可以放置图像或按钮而不是空白表,将其重定向以跟随其他用户?

以下是代码:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "InProfileCell", for: indexPath) as! ConnectionsCell

        if currentIndex == 1 {
            let user = followerusers[indexPath.row]
            cell.showFollowersUsers(val: user)
            print("follower")
        } else {
            let user = followingUsers[indexPath.row]
            cell.showFollowingUsers(val: user)
            print("following")
        }

        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if currentIndex == 0 {
            return followingUsers.count
        } else {
            return followerusers.count
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

1 个答案:

答案 0 :(得分:3)

numberOfRowscellForRow中的逻辑不一致。您的numberOfRows说明了

if currentIndex == 0 {
    followingUsers
} else {
    followerUsers
}

但是,您的cellForRow与此不一致,因为它声明了

if currentIndex == 1 { //NOTE THAT YOU ARE USING 1 HERE INSTEAD OF 0
    followerUsers
} else {
    followingUsers
}

现在当currentIndex为2时,numberOfRows将返回followerUsers的计数,但cellForRow会尝试访问followingUsers的值(而不是followerUsers)。这就是你让索引超出范围的原因。