0

My code compiles, but when I try to enter text, the simulator crashes and returns this error. Why?

import Foundation
import UIKit

protocol ListDetailViewControllerDelegate: class {
    func listDetailViewControllerDidCancel(_ controller: ListDetailViewController)
    func listDetailViewController(_ controller: ListDetailViewController, didFinishAdding checklist: Checklist)
    func listDetailViewController(_ controller: ListDetailViewController, didFinishEditing checklist: Checklist)
}

class ListDetailViewController: UITableViewController, UITextFieldDelegate {
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var doneBarButton: UIBarButtonItem!

    weak var delegate: ListDetailViewControllerDelegate?

    var checklistToEdit: Checklist?

    override func viewDidLoad() {
        super.viewDidLoad()

        if let checklist = checklistToEdit {
            title = "Edit Checklist"
            textField.text = checklist.name
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textField.becomeFirstResponder()
    }

    @IBAction func cancel() {
        delegate?.listDetailViewControllerDidCancel(self)
    }

    @IBAction func done() {
        if let checklist = checklistToEdit {
            checklist.name = textField.text!
            delegate?.listDetailViewController(self, didFinishEditing: checklist)
        } else {
            let checklist = Checklist(name: textField.text!)
            delegate?.listDetailViewController(self, didFinishAdding: checklist)
        }
    }

    override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        return nil
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        let oldText = textField.text! as NSString
        let newText = oldText.replacingCharacters(in: range, with: string) as NSString

        doneBarButton.isEnabled = (newText.length > 0) // EXC_BAD_INSTRUCTION
        return true
    }
}
pdenlinger
  • 3,897
  • 10
  • 60
  • 92
  • What exception (reason)? Not related but why do you cast `String` to `NSString`? – vadian Sep 09 '17 at 14:27
  • I want to bridge to NSString to add the replacingCharacters(). – pdenlinger Sep 09 '17 at 14:37
  • Error code: 2017-09-09 07:05:33.770764-0700 Checklists[68712:2792108] [Common] _BSMachError: port 7a03; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND" 2017-09-09 07:05:33.771541-0700 Checklists[68712:2792108] [Common] _BSMachError: port 7a03; (os/kern) invalid name (0xf) "Unable to deallocate send right" fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) – pdenlinger Sep 09 '17 at 14:38
  • 1
    `doneBarButton` is not connected in Interface Builder. – vadian Sep 09 '17 at 14:40

0 Answers0