ios - 数组索引超出范围

标签 ios swift parse-platform tableview

我有一个 tableView,我想在其中显示我的评论,例如 instagram 和许多其他社交网络的表现。帖子下方有 3 条评论,这里有一张图片来解释:enter image description here

正如您从该图片中看到的那样,顶部是帖子,然后是标题,最后是 3 条最新评论。

我在我的应用程序中添加了一个评论系统,当我点击评论图标时我可以查看所有评论,我被重定向到新的 VC。

当我添加标题时,每个帖子都有一个 UUID,所以我认为这可以在某种程度上帮助将评论连接到帖子!

但现在我正在寻求实现这一目标。

到目前为止,我已经在帖子下方的 Storyboard 中添加了 3 个 UIlabel,然后我为这些标签创建了一个集合 outlet。现在在我的表格 View 中,我有一个获取最新 3 条评论的查询:

var commentUsername = [String]()
var commentArray = [String]()


let Commentquery = PFQuery(className: "Comments")
Commentquery.whereKey("toPost", containedIn: self.uuidArray)
Commentquery.addDescendingOrder("createdAt")
Commentquery.limit = 3
Commentquery.findObjectsInBackgroundWithBlock({ (objects:[PFObject]?, error:NSError?) -> Void in
    if error == nil {
        self.commentUsername.removeAll(keepCapacity: false)
        self.commentArray.removeAll(keepCapacity: false)

        for object in objects! {
            self.commentArray.append(object.objectForKey("comment") as! String)
             self.commentUsername.append(object.objectForKey("username") as! String)
        }
        tableView.reloadData
     }
})

下面是我在 CellForRowAtIndexPath 中显示它们的方式:

var counter = (indexPath.row * 3)
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! NewsFeedTableViewCell

for comments in cell.threeComments{
    comments.text = commentArray[counter++]
    comments.sizeToFit()
}

正是在“comments.text = commentArray[counter++]”这一行,我得到了数组索引超出范围

我猜我收到这个错误是因为它要么返回 nil 因为没有对该照片的评论,要么没有至少 3 条评论来填充 UILabels...这就是我有一段时间遇到的困难现在,如果有人知道如何修复或更正可能的“可选”查询或一些很棒的东西!!

如需进一步说明,请在下方评论。

提前致以最诚挚的问候和感谢!

完整代码:

     var usernameArray = [String]()
    var profilePicture = [PFFile]()
    var dateArray = [NSDate?]()
    var postArray = [PFFile]()
    var titleArray = [String]()
    var uuidArray = [String]()
    var followArray = [String]()

    var commentUsername = [String]()
    var commentArray = [String]()



    override func viewDidLoad() {
        super.viewDidLoad()

        loadPosts()
    }



    func loadPosts() {
        let followQuery = PFQuery(className: "Follows")
        followQuery.whereKey("follower", equalTo: PFUser.currentUser()!.username!)
        followQuery.findObjectsInBackgroundWithBlock ({ (objects:[PFObject]?, error:NSError?) -> Void in
            if error == nil {
                self.followArray.removeAll(keepCapacity: false)

                for object in objects! {
                    self.followArray.append(object.valueForKey("following") as! String)

                }

                 self.followArray.append(PFUser.currentUser()!.username!)
                let query = PFQuery(className: "Posts")
                query.whereKey("username", containedIn: self.followArray)
                query.limit = self.page
                query.addDescendingOrder("createdAt")

                query.findObjectsInBackgroundWithBlock({ (objects:[PFObject]?, error:NSError?) -> Void in
                    if error == nil {

                        self.usernameArray.removeAll(keepCapacity: false)
                        self.profilePicture.removeAll(keepCapacity: false)
                        self.dateArray.removeAll(keepCapacity: false)
                        self.postArray.removeAll(keepCapacity: false)
                        self.titleArray.removeAll(keepCapacity: false)
                        self.uuidArray.removeAll(keepCapacity: false)

                        for object in objects! {

                            self.usernameArray.append(object.valueForKey("username") as! String)


                            self.profilePicture.append(object.valueForKey("profilePicture") as! PFFile)
                            self.dateArray.append(object.createdAt)
                            self.postArray.append(object.valueForKey("image") as! PFFile)
                            self.titleArray.append(object.valueForKey("caption") as! String)

                            self.uuidArray.append(object.valueForKey("uuid") as! String)


                        }

                        let Commentquery = PFQuery(className: "Comments")
                        Commentquery.whereKey("toPost", containedIn: self.uuidArray)
                        Commentquery.addDescendingOrder("createdAt")
                        Commentquery.limit = 3
                        Commentquery.findObjectsInBackgroundWithBlock({ (objects:[PFObject]?, error:NSError?) -> Void in
                            if error == nil {
                                self.commentUsername.removeAll(keepCapacity: false)
                                self.commentArray.removeAll(keepCapacity: false)

                                for object in objects! {
                                    self.commentArray.append(object.objectForKey("comment") as! String)
                                   self.commentUsername.append(object.objectForKey("username") as! String)

                                }


                                self.tableView.reloadData()


                            }else {
                                print(error?.localizedDescription)
                            }
                        })


                    } else {

                        print(error!.localizedDescription)
                        }
                })
            } else {
                print(error!.localizedDescription)
            }
        })

    }




    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }





    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
       return uuidArray.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {

          var counter = (indexPath.row * 3)

            let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! NewsFeedTableViewCell

        for comments in cell.threeComments{

                comments.text = commentArray[counter++]
                comments.sizeToFit()
    }


      }
}

最佳答案

在 tableview 函数 (CellForRowAtIndexPath) 内,indexPath.row 给出当前单元格索引号,无需使用循环进行迭代,如果需要 3 个单元格,则必须在

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return commentArray.count // you can set static number 3 here, instead of set 'commentArray.count'
}

.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! NewsFeedTableViewCell
    comments.text = commentArray[indexPath.row]
    comments.sizeToFit()
}

你可以这样改变你的循环

for (index, comments) in cell.threeComments {
    comments.text = commentArray[index]
    comments.sizeToFit()
}

关于ios - 数组索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785081/

相关文章:

ios - tvOS上的iCloud同步

ios - 字典取零

ios - 在 SwiftUI 中的 ForEach 内将拖动手势添加到图像

ios - 在 iOS EventKit 中自定义日历事件/提醒?

xcode - 为 OS X App 更改所选 NSTabView 选项卡的颜色

swift - 枚举协议(protocol)的默认实现

ios - 如何将保存的图像从 Parse.com 提取到我的应用程序中

ios - 丹尼尔金迪/图表 : get left yAxis width

ios - Xcode 6.3-Shell脚本调用错误(解析崩溃报告)

mysql - 如何在 MySQL 和 Parse.com 之间交换数据?