我想更新模型并在每次文本字段更改时执行验证。 我目前位于 textFieldDidEndEditing 委托(delegate)中,但我很难弄清楚要在 validateValue 方法中传递什么内容
func textFieldDidEndEditing(textField: UITextField) {
updateCustomObject() // sets the property to the value of the textfield
// What is the proper syntax here
customObject.validateValue(AutoreleasingUnsafeMutablePointer<AnyObject?>, forKeyPath: <String>)
}
最佳答案
在您的自定义对象中,覆盖 validateForInsert 和/或 validateForUpdate:
完成后,只需保存您的托管对象并捕获错误即可:
(这只是一个示例,不是工作代码...)
do {
try managedObjectContext.save()
catch {
if let validationError = error as? ValidationError {
//inform the user or do something useful here
}
}
您的自定义对象可能包含以下内容(示例,不完整或不工作)
enum ValidationError: ErrorType {
case TooLong
case TooShort
}
extension CustomObject {
override func validateForInsert() throws {
//similar to below
}
override func validateForUpdate() throws {
let success = //some conditions
if success == false {
throw ValidationError.TooLong
}
}
...
关于ios - 如何在 Swift 中从 textFieldDidEndEditing 调用 NSManagedObject validateValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33808252/