sdadsad sdadsad - 3 months ago 60
Swift Question

EXC_BREAKPOINT 0x00000000e7ffdefe in Crashlytics

I'm getting the following error in Crashlytics


LoginViewController.swift line 277
LoginViewController.textField(UITextField,
shouldChangeCharactersInRange : _NSRange, replacementString : String)
-> Bool


There's the code in my project:

// MARK: - UITextFieldDelegate
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField == txtSearch && string != "\n"{
var substring: String = textField.text!
substring = (substring as NSString).stringByReplacingCharactersInRange(range, withString: string)
self.searchAutocompleteEntriesWithSubstring(substring)
}
return true;
}


This error ocurrs only sometimes

Answer

You are force unwrapping your textField.text! which may be nil. Try below code:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == txtSearch && string != "\n"{
        if let text = textField.text {
            let substring = (text as NSString).stringByReplacingCharactersInRange(range, withString: string)
            self.searchAutocompleteEntriesWithSubstring(substring)
        }
    }
    return true
}