【问题标题】:Swift - Array index out of rangeSwift - 数组索引超出范围
【发布时间】:2015-12-24 09:34:26
【问题描述】:

我正在尝试用朋友行填充表格视图。当我运行代码时,它有时有效,有时无效。如果没有,它会显示以下错误:

致命错误:数组索引超出范围

类的代码在这里:

import UIKit
import Parse
import ParseUI

class ConnectionsViewController: PFQueryTableViewController  {

    var connectionObject = ConnectionClass()
    var userObject = UserClass()
    var friendsUsernamesListArray: [String] = []
    var friendsInfoListArray: [PFObject] = []


    func loadFriendsUsernames(completion: (result: [String]) -> Void)
    {
        print("1")

        let query = PFQuery(className:"FriendsConnections")

        query.whereKey("appUsername", equalTo:PFUser.currentUser()!["appUsername"])
        query.findObjectsInBackgroundWithBlock {
            (objects: [PFObject]?, error: NSError?) -> Void in

            if error == nil{
                self.friendsUsernamesListArray = objects![0]["friendsList"] as! NSArray as! [String]
                completion(result: self.friendsUsernamesListArray)


            }else{
                print(error)

            }

        }
    }

    func loadFriendsInfo()
    {
        print("2")
        let query : PFQuery = PFUser.query()!

        query.whereKey("appUsername", containedIn: self.friendsUsernamesListArray)
        query.findObjectsInBackgroundWithBlock {
            (objects: [PFObject]?, error: NSError?) -> Void in

            if error == nil{
                for item in objects! {
                    self.friendsInfoListArray.append(item)
                }
            }else{                
                print(error)
            }
        }
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        print("3")
    }

    override func queryForTable() -> PFQuery {
        print("4")
        self.loadFriendsUsernames({ (result)->Void in
            print("Inside Completion ")
            if(result.count > 0)
            {
                print("Completion - Array not empty")
                self.loadFriendsInfo()
            }else{
                print("Completion - Array empty")
            }

        })

        let query = PFQuery(className: "FriendsConnections")
        query.cachePolicy = .NetworkOnly
        query.orderByAscending("createdAt")
        return query
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
        print("5")
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ConnectionTableCell

        //print("Array Content: \(friendsInfoListArray)")



        if(indexPath.row >= 0)
        {

            cell.connectionNameLabel.text = self.friendsInfoListArray[indexPath.row]["name"] as? String

        }else{
            print("Something going wrong populating the cell")
        }
        return cell
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        print("6")
        if indexPath.row + 1 > self.objects?.count
        {
            return 44
        }

        let height = super.tableView(tableView, heightForRowAtIndexPath: indexPath)
        return height
    }


    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        print("7")
        /*Get all data of friend clicked and pass to next view*/
        self.userObject.name = friendsInfoListArray[indexPath.row]["name"] as? String
        self.userObject.username = friendsInfoListArray[indexPath.row]["appUsername"] as? String
        self.userObject.email = friendsInfoListArray[indexPath.row]["email"] as? String
        self.userObject.mobile = friendsInfoListArray[indexPath.row]["mobile"] as? String


        let tempWorkAddress = friendsInfoListArray[indexPath.row]["workAddress"] as! NSArray as! [String]
        let tempHomeAddress = friendsInfoListArray[indexPath.row]["homeAddress"] as! NSArray as! [String]



        /*Handle addresses where empty*/
        if(tempHomeAddress.isEmpty || tempWorkAddress.isEmpty)
        {
            self.userObject.homeAddress.append("")
            self.userObject.homeAddress.append("")
            self.userObject.workAddress.append("")
            self.userObject.workAddress.append("")
        }else{
            self.userObject.homeAddress = friendsInfoListArray[indexPath.row]["homeAddress"] as! NSArray as! [String]
            self.userObject.workAddress = friendsInfoListArray[indexPath.row]["workAddress"] as! NSArray as! [String]

        }


        //to get the image file
        if let userImageFile = friendsInfoListArray[indexPath.row]["ProfilePic"] as? PFFile {
            userImageFile.getDataInBackgroundWithBlock {
                (imageData: NSData?, error: NSError?) -> Void in
                if error == nil {
                    if let imageData = imageData {
                        self.userObject.userProfilePic = UIImage(data:imageData)
                    }
                }else{
                    self.userObject.userProfilePic = nil
                    print(error)
                }
            }

        }else{
            self.userObject.userProfilePic = nil
        }


        self.performSegueWithIdentifier("showConnectionDetailsSegue", sender: self)

    }

    /*override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.friendsUsernamesListArray.count
    }*/

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        print("8")
        if (segue.identifier == "showConnectionDetailsSegue") {
            // pass data to next view
            print(segue.description)
            let destinationVC = segue.destinationViewController as! FriendDetailViewController
            destinationVC.userObject = self.userObject;

        }
    }

}

执行失败时的调试器会高亮这一行:

    cell.connectionNameLabel.text = self.friendsInfoListArray[indexPath.row]["name"] as? String

现在我添加了带有数字的打印语句以查看流程,如下所示:

4
1
3
Inside Completion 
Completion - Array not empty
2
6
6
5
6
fatal error: Array index out of range

任何帮助将不胜感激,因为我在这个问题上几天没有解决方案。

【问题讨论】:

  • tableView(tableView, numberOfRowsInSection) 用的是什么?它被注释掉了......你的测试if(indexPath.row >= 0)也没有意义,它应该是if indexPath.row < self.friendsInfoListArray.count
  • @Grimxn 我之前尝试更改 if 语句,但没有成功。它打印空单元格并触发其他部分。我现在也试过了,还是一样
  • 此外,每当 friendsInfoListArraydatasource 更新时,您应该在 tableView 上调用 reloadData
  • 请取消注释numberOfRowsInSection并使用return self.friendsInfoListArray.count
  • @san 我注释掉它的原因是当我把它留在里面时,表格行中不再显示任何内容。

标签: ios arrays xcode swift parse-platform


【解决方案1】:

看看这个方法

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell?

并开始调试,因为您的方法试图获取数组外的项目。

例子:

var myArray = [0,1,2,3];
myArray[0] // 0

在你的情况下:

var myArray = [0,1,2,3];
myArray[4] // Error!

给你的小帮助问题:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
        print("5")
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ConnectionTableCell

        //print("Array Content: \(friendsInfoListArray)")

        if (self.friendsInfoListArray.count < indexPath.row) {
           print("PROBLEM")
        }

        if(indexPath.row >= 0)
        {

            cell.connectionNameLabel.text = self.friendsInfoListArray[indexPath.row]["name"] as? String

        }else{
            print("Something going wrong populating the cell")
        }
        return cell
    }

【讨论】:

  • 只是为了澄清错误没有发生在那里。一旦记录加载(当它们加载并且没有失败时),我就可以通过这种方法成功地将数据转换到详细视图。该问题是在方法 cellForRowAtIndexPath 中在线触发的
  • @ksa_coder yap 方法名称错误抱歉,尝试打印您尝试使用的索引路径以及您的数组计数是多少
  • 打印 friendsInfoListArray.count 并打印 indexPath.row 你会看到
  • 我现在试过了,它显示: print("Index Path Row: (indexPath.row)") 显示为 0 并且 print("Array Count: (friendsUsernamesListArray.count)") 显示为 2
  • 我添加了您在上面添加的检查...即使出于相同原因执行失败,问题语句也没有打印
【解决方案2】:

在分段数法中,你需要这样做:

返回数组.count

就是这样。

【讨论】:

    猜你喜欢
    • 2016-11-10
    • 2017-01-05
    • 2017-05-14
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多