I’m working on trying to use Core Data to populate a dropdown list. A couple of things I wasn’t sure of though. I am trying to create a “Game” or “Fixture” for my teams. So this screen lists, what date this game is happening, who I’m playing against and which one of my teams are playing in this game.
Here is some of my code:
override func viewDidLoad() {
super.viewDidLoad()
// add input view for date
self.pickerView = UIPickerView()
pickerView.showsSelectionIndicator = true
pickerView.delegate = self
// load date for UIPicker
let fetchRequest = NSFetchRequest(entityName: "Team")
let sort = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sort]
do {
teamUIpickerArray = try (managedObjectContext.executeFetchRequest(fetchRequest) as? [Team])!
// success ...
} catch let error as NSError {
// failure
print("Fetch failed: \(error.localizedDescription)")
}
teamNameTextField.inputView = pickerView
teamNameTextField.inputAccessoryView = toolBarSetUp()
}
I also added in the PickerView Methods
// The number of columns of data
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
// The number of rows of data
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if teamNameTextField.isFirstResponder(){
return teamUIpickerArray.count
}
return 1
}
// The data to return for the row and component (column) that's being passed in
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if teamNameTextField.isFirstResponder(){
return teamUIpickerArray [row]
}
return nil
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if teamNameTextField.isFirstResponder(){
teamNameTextField.text = teamUIpickerArray[row]
}
}
The Team is a relation in this “Game” model. The last two picker functions both fail with
Type [Team]! Has no subscript members.
So a couple of things for me were, I wasn’t sure why this was failing and what is wrong? I assumed that I would have to make is teamUIpickerArray.name[row]
so that my UIPicker would display the name of the team this game is for. But that doesn’t seem possible.
And a follow on, how when I select a certain team in the UIPicker, do I let xcode know that I am saving the Team Object (as a relation) and not just the Team.name “String”. Hope that makes sense?