数组索引超出范围

数组索引超出范围

我正在尝试用几行朋友填充表格视图。当我运行代码时,它有时可以工作,有时不能。如果没有,则显示以下错误:


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


该类的代码在这里:

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


感谢您的帮助,因为我连续几天都没有解决此问题。

最佳答案

看这个方法

 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
    }

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

10-09 16:14