Search code examples
arraysswiftxcodecore-datauipickerview

Display values for PickerView from Core Database


I'm a new IOS developer. I'm using Xcode 8 and swift 3. I want to display values into the pickerView from data saved in Core database. My code bellow has an error (fatal error: Index out of range)

I define an array to hold the fetched data from the Core database

  var boundName  = [String]()
  var expenses = [NSManagedObject]()// variable to fetch the data from core database
  var num = 0// variable to hold the count of the fetched data

here are the functions for the pickerView

public func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1;
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    let request = NSFetchRequest <NSFetchRequestResult> (entityName : "ExpenseBound_Table")
    request.returnsObjectsAsFaults = false


    do {
        expenses = try self.context.fetch(request) as! [NSManagedObject]
       num = expenses.count

    } catch { print(error) }

    return num;
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {


    let request = NSFetchRequest <NSFetchRequestResult> (entityName : "ExpenseBound_Table")
    request.returnsObjectsAsFaults = false

    do{
    expenses = try self.context.fetch(request) as! [NSManagedObject]

        if expenses.count > 0 {


              let person = expenses[row] 
               let boundText = person.value(forKey: "boundName_Expense" ) as? String
              boundName [row] = boundText! //error fires here fatal error: Index out of range




        }

    }
    catch{
        print ("Fetch Faield")
    }
    return boundName[row]
}

Solution

  • The array is declared using:

    var boundName = [String]()
    

    Declaration in this way does not specify the size of the array so when you run the following line, it will crash:

    boundName [row] = boundText!
    

    Solution:

    Use append instead:

    boundName.append(boundText!)