从数组索引表视图超出范围 [英] Table view from array index out of range

查看:189
本文介绍了从数组索引表视图超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个数组来从数据库中读取数据,目前,我有数组中的8个项目。我试图做一个表,其中我有一个节头。目前,我有4个部分,我已经设置正确,它工作。它也可以运行在第一时间,但是当我尝试滚动回我得到一个索引超出范围。我使用的myArray的[myindex]设置每个项目的单元格的数据,并且不工作。

看来,我需要我的数据分解成一个只包含数据的每个部分正确让表视图控制这4个部分。这些数据可以包含任意数量的部分。

有没有更好的方法来做到这一点?

我附上一个图片来说明问题。

感谢

根据要求添加code。

 覆盖FUNC numberOfSectionsInTableView(的tableView:UITableView的) -  GT; INT {
    //指令#warning未完全执行,返回段数
    打印(回归节 - > \\(部分))
    返回段//似乎工作
}覆盖FUNC的tableView(的tableView:UITableView的,numberOfRowsInSection段中:int) - GT; INT {
    //指令#warning不完整的实现,则返回的行数
    打印(返回部分的行数 - > \\(noRowsInSection [节]))
    返回noRowsInSection [段] //似乎工作
}
覆盖FUNC的tableView(的tableView:UITableView的,titleForHeaderInSection段中:int) - GT;串? {
    返回sectionHeader [段] //似乎工作
}
覆盖FUNC的tableView(的tableView:UITableView的,willDisplayHeaderView观点:UIView的,forSection部分:智力){
    //格式节标题
    让头:UITableViewHeaderFooterView =查看! UITableViewHeaderFooterView
    header.textLabel!.textColor = UIColor.blueColor()
    UIColor.blueColor()
    header.textLabel!.font = UIFont.boldSystemFontOfSize(12)
    header.textLabel!.frame = header.frame
    header.textLabel!.textAlignment = NSTextAlignment.Right
}
覆盖FUNC的tableView(的tableView:UITableView的,的cellForRowAtIndexPath indexPath:NSIndexPath) - GT; {的UITableViewCell
    让细胞= tableView.dequeueReusableCellWithIdentifier(OurCell,forIndexPath:indexPath)作为! OurTableViewCell
    打印(myindex - > \\(myindex)行 - > \\(indexPath.row))
    cell.OurCellLabel.text = MyHouses [myindex] .getAddressDetails()//结束配置houses.cell
    //cell.OurCellLabel.text = MyHouses [indexPath.row] .getAddressDetails()//结束配置houses.cell
    myindex ++ //问题就在这里 - 熄灭范围
    回报细胞
}

在这里,我从sqlite的数据库获取数据

  FUNC GetListOfHousesFromDB(){
    让DOCSDIR = dirPaths [0]
    让databasePath = docsDir.stringByAppendingString(/ newdb.db)
    如果fileMgr.fileExistsAtPath(databasePath为String){
        让houseDB = FMDatabase(路径:databasePath为String)
        如果houseDB.open(){
            VAR noRows:= 0
            VAR SQL =SELECT COUNT(地址),从房屋CNT//定义查询
            houseDB.executeStatements(SQL)//执行查询
            让结果:FMResultSet? = houseDB.executeQuery(SQL,withArgumentsInArray:无)//从查询结果
            如果结果?。接下来()==真{
                让CNT =(结果吗?.stringForColumn(CNT))! //获得行数从DB
                noRows = INT(CNT)!
            }
            变种I = 0
            SQL =SELECT从房屋ORDER BY省份,城市,街道,地址地址,街道,城市,省,邮编//定义查询
            houseDB.executeStatements(SQL)//执行查询
            让结果2:FMResultSet? = houseDB.executeQuery(SQL,withArgumentsInArray:无)//从查询结果
            而结果2?。接下来()==真{
                MyHouses.append(纽豪斯())
                MyHouses [I]。地址=(结果2?.stringForColumn(地址))!
                MyHouses [I] .street =(结果2?.stringForColumn(街道))!
                MyHouses [I]。城市=(结果2?.stringForColumn(城市))!
                MyHouses [I] .STATE =(结果2?.stringForColumn(国家))!
                MyHouses [I] .zip文件=(结果2?.stringForColumn(ZIP))!
                打印(地址 - > \\(我)\\(MyHouses [I] .getAddressDetails()))
                我++
            }
        }
        houseDB.close()
    }
}


解决方案

根据您的其他<一href=\"http://stackoverflow.com/questions/34163054/define-object-with-multidimensional-properties/34163684#34163684\">post,你需要的是用于处理数据表格显示的更新模型和更新的数据结构。


  

家 - Model类


 结构房子{
    VAR地址:字符串
    VAR街道:字符串
    VAR城市:字符串
    VAR状态:字符串
    VAR邮编:字符串    FUNC getAddressDetails() - &GT;字符串{
        回归\\(地址)\\(街道)\\(市)\\(州)\\(ZIP)
    }    FUNC getCityState() - &GT;字符串{
        回归\\(市) - \\(州)
    }
}


  

助手类加载数据。


 类HouseDataHelper {    私有静态让_sharedInstance = HouseDataHelper()
    VAR myHouses:字典&LT;弦乐,[家]&GT; = [:]    私有的init(){
        loadHouseData()
    }    静态FUNC sharedInstance() - GT; HouseDataHelper {
        返回_sharedInstance
    }    私人FUNC loadHouseData(){
        VAR房子= [豪斯()        //这里您填充实际值。 GetListOfHousesFromDB()        //加载测试假人的数据
        变种sectionHeader =
        因为我在0 ... 4 {
            sectionHeader =头\\(I)
            房子+ = [楼(地址:地址1,街头:Street1,市City1状态:状态1,邮政编码:ZIP1)]
            房子+ = [楼(地址:地址2,街头:STREET2,市城2,状态:状态2,邮编:拉链码)]
            房子+ = [楼(地址:地址3,街头:Street3城市:请分享帮助状态:状态3,邮政编码:Zip3)]
            房子+ = [楼(地址:地址4,街头:Street4,市City4状态:State4,邮政编码:Zip4)]
            房子+ = [楼(地址:Address5,街头:Street5,市City5状态:State5,邮政编码:Zip5)]            myHouses.updateValue(房屋,forKey:sectionHeader)
            房屋= []
        }
    }
}


  

表视图控制器


 类TableViewController:{的UITableViewController    VAR房子= HouseDataHelper.sharedInstance()。myHouses
    VAR sectionHeaders:[字符串] = []    覆盖FUNC viewWillAppear中(动画:BOOL){
        super.viewWillAppear(动画)        sectionHeaders =阵列(houses.keys.sort())
    }    覆盖FUNC numberOfSectionsInTableView(的tableView:UITableView的) - GT; INT {
        回报houses.count
    }    覆盖FUNC的tableView(的tableView:UITableView的,numberOfRowsInSection段中:int) - GT; INT {
        如果让行=房屋[sectionHeaders [节]] {
            回报rows.count
        }        返回0
    }    覆盖FUNC的tableView(的tableView:UITableView的,titleForHeaderInSection段中:int) - GT;串? {
        返回sectionHeaders [段]
    }    覆盖FUNC的tableView(的tableView:UITableView的,的cellForRowAtIndexPath indexPath:NSIndexPath) - GT; {的UITableViewCell
        //基于房子填充细胞
    }
}

I'm using an array to read data from a database, Currently I have 8 items in the array. I am trying to make a table where I have a section header. Currently I have 4 sections and I have set that properly and it works. It also works running the first time but when I try to scroll back I get an index out of range. I am using myarray[myindex] to set the cell data for each item and that is not working.

It seems that I need to break up my data into 4 sections that contains only the data for each section to let the table view control it properly. The data can contain any number of sections.

Is there a better way to do this?

I have attached a pic to describe the problem.

Thanks

Adding code on request.

  override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    print("Returning Sections - > \(sections)")
    return sections //seems to work
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    print("Return number of rows in section -> \(noRowsInSection[section])")
    return noRowsInSection[section] // seems to work
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sectionHeader[section] // seems to work
}
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    // Format for section Headers
    let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    header.textLabel!.textColor = UIColor.blueColor()
    UIColor.blueColor()
    header.textLabel!.font = UIFont.boldSystemFontOfSize(12)
    header.textLabel!.frame = header.frame
    header.textLabel!.textAlignment = NSTextAlignment.Right
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("OurCell", forIndexPath: indexPath) as! OurTableViewCell
    print("myindex - > \(myindex) row -> \(indexPath.row)")
    cell.OurCellLabel.text = MyHouses[myindex].getAddressDetails()        // End configure houses.cell
    //cell.OurCellLabel.text = MyHouses[indexPath.row].getAddressDetails()        // End configure houses.cell
    myindex++ // PROBLEM HERE - GOES OUT OF RANGE
    return cell
}

Here I am getting data from the sqlite DB

func GetListOfHousesFromDB() {
    let docsDir = dirPaths[0]
    let databasePath = docsDir.stringByAppendingString("/newdb.db")
    if fileMgr.fileExistsAtPath(databasePath as String) {
        let houseDB = FMDatabase(path: databasePath as String)
        if houseDB.open() {
            var noRows: Int = 0
            var sql = "select count(Address) as cnt from Houses" // Define Query
            houseDB.executeStatements(sql) // Execute Query
            let results:FMResultSet? = houseDB.executeQuery(sql,withArgumentsInArray: nil) //Get results from Query
            if results?.next() == true {
                let cnt = (results?.stringForColumn("cnt"))! // Retrieve number of rows from DB
                noRows = Int(cnt)!
            }
            var i = 0
            sql = "SELECT Address, Street, City, State, Zip from Houses ORDER BY State, City, Street, Address" // Define Query
            houseDB.executeStatements(sql) // Execute Query
            let results2:FMResultSet? = houseDB.executeQuery(sql,withArgumentsInArray: nil) // Get results from Query
            while results2?.next() == true {
                MyHouses.append(newhouse())
                MyHouses[i].address = (results2?.stringForColumn("Address"))!
                MyHouses[i].street = (results2?.stringForColumn("Street"))!
                MyHouses[i].city = (results2?.stringForColumn("City"))!
                MyHouses[i].state = (results2?.stringForColumn("State"))!
                MyHouses[i].zip = (results2?.stringForColumn("Zip"))!
                print("Address -> \(i) \(MyHouses[i].getAddressDetails())")
                i++
            }
        }
        houseDB.close()
    }
}

解决方案

Based on your other post, what you need is an updated House model and updated data structure for handling data for your table view.

House - Model class

struct House {
    var address: String
    var street: String
    var city: String
    var state: String
    var zip: String

    func getAddressDetails() -> String {
        return "\(address) \(street) \(city) \(state) \(zip)"
    }

    func getCityState() -> String {
        return "\(city) - \(state)"
    }
}  

Helper Class for loading data

class HouseDataHelper {

    private static let _sharedInstance = HouseDataHelper()
    var myHouses: Dictionary<String, [House]> = [:]

    private init() {
        loadHouseData()
    }

    static func sharedInstance() -> HouseDataHelper {
        return _sharedInstance
    }

    private func loadHouseData() {
        var houses = [House]()

        //Populating your actual values here. GetListOfHousesFromDB()

        //Loading dummy data for testing
        var sectionHeader = ""
        for i in 0...4 {
            sectionHeader = "Header \(i)"
            houses += [House(address: "Address1", street: "Street1", city: "City1", state: "State1", zip: "Zip1")]
            houses += [House(address: "Address2", street: "Street2", city: "City2", state: "State2", zip: "Zip2")]
            houses += [House(address: "Address3", street: "Street3", city: "City3", state: "State3", zip: "Zip3")]
            houses += [House(address: "Address4", street: "Street4", city: "City4", state: "State4", zip: "Zip4")]
            houses += [House(address: "Address5", street: "Street5", city: "City5", state: "State5", zip: "Zip5")]

            myHouses.updateValue(houses, forKey: sectionHeader)
            houses = []
        }
    }
}

Table View Controller

class TableViewController: UITableViewController {

    var houses = HouseDataHelper.sharedInstance().myHouses
    var sectionHeaders: [String] = []

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        sectionHeaders = Array(houses.keys.sort())
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return houses.count
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let rows = houses[sectionHeaders[section]] {
            return rows.count
        }

        return 0
    }

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sectionHeaders[section]
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //Populate cells based on "houses"
    }
}

这篇关于从数组索引表视图超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆