简体   繁体   English

Swift-数组索引超出范围

[英]Swift - Array index out of range

I am attempting to populate a table view with rows of friends. 我正在尝试用几行朋友填充表格视图。 When I run the code, it sometimes works and sometimes doesn't. 当我运行代码时,它有时可以工作,有时却不能。 When it doesn't, it shows the following error: 如果没有,则显示以下错误:

fatal error: Array index out of range 致命错误:数组索引超出范围

The code for the class is here: 该类的代码在这里:

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;

        }
    }

}

The debugger when the execution fails highlight this line: 执行失败时,调试器突出显示以下行:

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

Now I added print statements with numbers to see the flow, and it is as following: 现在,我添加了带有数字的打印语句以查看流程,如下所示:

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

Any help will be appreciated since I am on this problem for couple of days without a solution. 感谢您的帮助,因为我连续几天都没有解决此问题。

Look at this method 看这个方法

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

And start debugging, because you method trying to take item that is out of array. 并开始调试,因为您尝试获取没有阵列的项目。

Example: 例:

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

In your case: 在您的情况下:

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

Small help issue for you: 为您提供的小帮助问题:

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
    }

in the number of sections method , you need to do this : 在“节数”方法中,您需要这样做:

return array.count 返回array.count

thats it. 而已。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM