L.Vl
L.Vl

Reputation: 113

Populate an array for the tableView section and the tableView cell, swift

I am trying to implement a TableView like Instagram with one row per section.

I would like to populate two arrays :

first sectionArray to get the row data in function of the section

and object to get the Name of the section.

But when I try to populate sectionArray, I get an error : "fatal error: Array index out of range"

Do you have an idea of how to fix it??

Thanks!

    import UIKit
    import ParseUI
    import Parse

    class TableView: UIViewController, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate {


        @IBOutlet weak var tableView : UITableView?


        var sectionArray : [[PFFile]] = []


        override func viewDidLoad() {
            super.viewDidLoad()

            self.loadCollectionViewData()

        }


        var object = [PFObject]()

        func loadCollectionViewData() {

            let query = PFQuery(className: "Myclass")

            // Fetch data from the parse platform
            query.findObjectsInBackgroundWithBlock {
                (objects: [PFObject]?, error: NSError?) -> Void in

                // The find succeeded now rocess the found objects into the countries array
                if error == nil {

                    // Clear existing country data
                    self.object.removeAll(keepCapacity: true)

                    // Add country objects to our array
                    if let objects = objects as [PFObject]? {
                        self.object = Array(objects.generate())

                        let index = self.object.count as Int
                        print (index)

                        for i in 1...index {
                            //error here!
                            if let finalImage = self.object[i]["image"] as? [PFFile]
                            {
                                self.sectionArray[i] = finalImage

                                print(self.sectionArray[i])
                            }

                        }
                    }

                    // reload our data into the collection view
                    self.tableView?.reloadData()

                } else {
                    // Log details of the failure
                    print("Error: \(error!) ")
                }
            }
        }

        func numberOfSectionsInTableView(tableView: UITableView) -> Int {

            return sectionArray.count
        }

        func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


            return sectionArray[section].count

        }

        func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            if section < self.object.count {
                if let namelabel = object[section]["Name"] as? String {
                    return namelabel
                }
            }

            return nil
        }

        func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 30
        }


        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

            var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! ListControllerViewCell!
            if cell == nil
            {
                cell = ListControllerViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
            }

            if let finalImage = sectionArray[indexPath.section][indexPath.row] as? PFFile   //object[indexPath.row]["image"] as? PFFile
            {

                finalImage.getDataInBackgroundWithBlock{(imageData: NSData?, error: NSError?) -> Void in
                    if error == nil
                    {
                        if let imageData = imageData
                            {
                                cell.ImagePromo!.image = UIImage(data:imageData)
                            }

                    }

            }


            if let CommentLabel = sectionArray[indexPath.section][indexPath.row]
            //object[indexPath.row]["Comment"] as? String
            {
                cell.CommentLabel!.text = CommentLabel
                cell.CommentLabel!.adjustsFontSizeToFitWidth = true
            }

            return cell;
        }

    }

Upvotes: 0

Views: 1577

Answers (2)

Bharat Modi
Bharat Modi

Reputation: 4180

Try adding Exception Breakpoint to catch the error location exactly,

Also edit your datasource as,

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

       if(sectionArray.count != 0) {
        return sectionArray.count
       } else {
        return 0;
       }
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

       if(sectionArray.count < section) {
          return sectionArray[section].count
       } else {
          return 0;
       }      
}

Upvotes: 0

H4Hugo
H4Hugo

Reputation: 2650

You have a problem in your for in loop :

You should start at 0, not 1 so your call to the loop looks like :

for i in 0..<index

This is the "danger" with for-in loops compared to C-style loops. You are looping the correct number of times, but you exceed your array size by 1 because you are starting at the wrong index.

Upvotes: 1

Related Questions