【问题标题】:Array index out of range数组索引超出范围
【发布时间】:2016-03-03 23:23:10
【问题描述】:

我有一个 tableView,我想在其中显示我的 cmets,例如 instagram 和许多其他社交网络的表现。帖子下方3 cmets,来一张图解释一下:

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

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

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

但现在我正在努力实现这一目标。

到目前为止,我在帖子下方的故事板中添加了 3 个 UIlabels,然后我为这些标签创建了一个集合出口。现在在我的表格视图中,我有一个获取最新 3 cmets 的查询:

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()
}

在“cmets.text = commentArray[counter++]”那一行,我得到数组索引超出范围

我猜我收到了这个错误,因为它要么返回 nil,因为那张照片没有 cmets,要么没有至少 3 个 cmets 来填充 UILabel ......这就是我有一段时间遇到的困难现在,如果有人知道如何修复或正确可能的“可选”查询或其他东西会很棒!

如需进一步解释,请在下方评论。

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

完整代码:

     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()
    }


      }
}

【问题讨论】:

  • 更好的方法是使用 2D 数组作为 commentUsername,然后您可以直接遍历事物,而不是假设每个集合中的硬编码数量

标签: ios swift parse-platform tableview


【解决方案1】:

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()
}

【讨论】:

  • 嘿,谢谢,但我不确定如果我需要的是三个单元格...因为会有一张照片等全部包含在 1 个单元格中...我需要在其中显示 3 条评论那个细胞不是吗?因为如果我为评论重复 3 次,那么图像会不会重复..?
  • @Jack你能把整个viewController代码块放在这里然后我就可以理解问题了..(commentArray结构和uitableview委托和数据源方法也足够了)
  • 嗨,我在上面添加了大部分内容
  • 在您的 numberOfRowsInSection 方法中返回 1 表示您有一个单元格,但在 cellForRowAtIndexPath indexpath.row 是 0 索引 (0,1,2,3,..) 您只有一个单元格,因此当前值indexpath.row = 0 的,因此 (indexpath.row*3) == 0
  • 在 for in 循环之前,打印变量然后你可以得到这个想法,例如: print(cell.threeComments.count) print(counter) print(commentArray)
【解决方案2】:

@Jack - 我认为解决方案将与您的其他问题 https://stackoverflow.com/questions/35854857/how-to-order-2-tableview-sections/35866457?noredirect=1#comment59402360_35866457 非常相似,您应该考虑将用户名和评论文本存储在结构中,并将查询结果加载到其中。

如果所有内容都加载到名为 comments 的数组中,那么您仍然可以选择 - 使用单个标签显示所有三行(在情节提要中设置行数 = 3),或者使用三个标签

// single label
myLabel.text = ""
for comment in comments
{
    myLabel.text += comment.text + "\n"
}

// multiple labels approach, assuming labels have tag value 100, 101, 102
for index in 0..<comments.count
{
    let label = cell.contentView.viewWithTag(100 + index) as! UILabel 
    label.text = comments[index]
}

** 更新 - cell.contentView.viewWithTag **

我使用了从 100 而不是 0 开始的标记值,以避免与默认值发生意外匹配

这是设置tag 值的方法。在这个例子中,我有两个自定义单元格,黄色单元格有三个标签。如果依次选择每个标签,并如图所示设置 Tag 属性,则创建的每个单元格实例都将具有具有相同标签的这三个标签 - 但您只能在单个单元格的上下文中搜索,所以其他实例无关紧要。

【讨论】:

  • 我想我已经成功了,只是不确定标签位...如何在 tableViewCell 文件中添加标签?
  • 所以我不需要为标签做一个出口?
  • 好了,可以了,有空可以查一下聊天记录吗!
  • 好吧 - 你可以,但更明智的是使用奥特莱斯系列而不是单个奥特莱斯 - 但它实际上与我们在这里所做的事情相同
【解决方案3】:

这个设计需要改进,(见评论)但为了避免崩溃,你可以简单地这样做:

for comments in cell.threeComments{
     if commentsArray.count < counter {
         comments.text = commentArray[counter]
         comments.sizeToFit()
     }
     counter += 1
}

仅供参考,我删除了 counter++,因为在 Swift 3.0 中删除了一元运算符

【讨论】:

  • 我试过了,但似乎还是得到了错误......你会推荐什么方法?你会怎么做? ——
猜你喜欢
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多