Ios Swift-数组索引超出范围

Ios Swift-数组索引超出范围,ios,arrays,xcode,swift,parse-platform,Ios,Arrays,Xcode,Swift,Parse Platform,我正在尝试用一行好友填充表视图。当我运行代码时,它有时有效,有时无效。否则,将显示以下错误: 致命错误:数组索引超出范围 该类的代码如下所示: import UIKit import Parse import ParseUI class ConnectionsViewController: PFQueryTableViewController { var connectionObject = ConnectionClass() var userObject = UserCl

我正在尝试用一行好友填充表视图。当我运行代码时,它有时有效,有时无效。否则,将显示以下错误:

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

该类的代码如下所示:

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
现在我添加了带数字的print语句来查看流程,如下所示:

4
1
3
Inside Completion 
Completion - Array not empty
2
6
6
5
6
fatal error: Array index out of range
任何帮助将不胜感激,因为我在这个问题上的两天没有解决方案

看看这个方法

 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
    }
override func tableView(tableView:UITableView,cellForRowAtIndexPath:nsindepath,object:PFObject?)->pftableview单元格?{
打印(“5”)
让cell=tableView.dequeueReusableCellWithIdentifier(“cell”,forIndexPath:indexPath)作为!ConnectionTableCell
//打印(“数组内容:\(FriendsInfolisStarray)”)
if(self.friendsinfolisStarray.count=0)
{
cell.connectionNameLabel.text=self.FriendsInfolisStarray[indexPath.row][“name”]作为?字符串
}否则{
打印(“填充单元格时出错”)
}
返回单元
}

在节数方法中,您需要执行以下操作:

返回数组.count


就是这样。

只是为了澄清错误没有发生在那里。一旦记录加载(当它们加载并且没有失败时),我就能够通过这种方法成功地将数据转换到详细视图。该问题是通过在线输入方法触发的cellForRowAtIndexPath@ksa_coderyap错误的方法名称抱歉,请尝试打印您尝试使用的索引路径以及您正在使用的数组countprint FriendsInfolisStarray.count和print indexPath.row,您将看到我现在尝试了,结果显示:print(“索引路径行:(indexPath.row)”)显示为0和print(“数组计数:(friendsUsernamesListArray.Count)”)显示为2I添加了您在上面添加的检查…即使执行失败,问题语句也不会打印,原因相同您在
tableView(tableView,numberOfRowsInSection)
中使用的是什么?它被注释掉了…如果(indexPath.row>=0,您的测试也是
没有任何意义,它应该是
if indexath.row
@Grimxn我之前试图更改if语句,但没有起作用。它打印空单元格并触发了else部分。我现在也尝试了,但仍然是一样的。因此,每当更新FriendsFolisStarray即数据源时,都应该调用reloadDataTableView请取消注释
numberOfRowsInSection
并使用
返回self.FriendsInFolisStarray.count
@san我之所以将其注释掉,是因为当我将其保留在中时,表行中不再显示任何内容。