0

I am trying to implement a UIPickerView to my App. Though I haven't got an error, when I run the app it crashes with following error:

unexpectedly found nil while unwrapping an Optional value

class LobbyViewController: UIViewController {


   @IBOutlet weak var textfield: UITextField!
   var picker: UIPickerView!

   var radius = [2, 5, 10, 15, 20, 25, 50, 100, 1000]


   override func viewDidLoad() {
        super.viewDidLoad()
        picker.dataSource = self
        picker.delegate = self
        self.textfield.inputView = picker
   }

   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }

}

extension LobbyViewController: UIPickerViewDataSource {

   func numberOfComponentsInPickerView(picker: UIPickerView!) -> Int
   {
       return 1
   }

   func pickerView(picker: UIPickerView!, numberOfRowsInComponent component: Int) -> Int{
       return radius.count
   }

}

extension LobbyViewController: UIPickerViewDelegate{
    func pickerView(umkreisPicker: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String {
        return radius[row]
    }

}

Hope you can help me!

McLawrence
  • 4,975
  • 7
  • 39
  • 51
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Cristik Mar 19 '18 at 06:07

2 Answers2

2

You aren't ever creating your UIPickerView instance - either picker should be marked as an @IBOutlet and hooked up in your storyboard or you should create it before setting the delegate and data source.

Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
Nate Cook
  • 92,417
  • 32
  • 217
  • 178
1

Any hint as to which line this is happening on? My guess would be picker.dataSource = self

You do not have this set up as an outlet and it's never initialized anywhere according to what you've shared.

EDIT FOR COMMENT

So you need to initialize the picker, you can do that like you initialize most things, with it's standard init() method. Then you need to tell the text field that it's input view should be the picker.

Try adding the following to viewDidLoad()

picker = UIPickerView()
textField.inputView = picker
Chris Wagner
  • 20,773
  • 8
  • 74
  • 95
  • yes. its the 'picker.dataSource = self' line. it shoud pop up, when the textfield is edited in the app, so I did not connect it to an outlet. How can I initialize it. Haven't found something to the initalizer in the documentary. Thanks for your help! – McLawrence Aug 14 '14 at 17:43
  • Updated to address your comment – Chris Wagner Aug 14 '14 at 19:02