ios - 如何在 Swift 中从 textFieldDidEndEditing 调用 NSManagedObject validateValue

标签 ios swift core-data

我想更新模型并在每次文本字段更改时执行验证。 我目前位于 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/

相关文章:

swift - 泛型和协议(protocol)类型的功能参数在实践中有什么区别?

ios - Xcode SwiftGen : build fails in project with multiple targets

ios - UIStoryboard 更改标签栏按钮文本

ios - UIAlertController 之间的转换

arrays - 如何创建具有大小的 Swift 空二维数组

ios - iOS 的数据存储选项

arrays - 结构数组 : How to save in coredata?

multithreading - 核心数据和多线程(和绑定(bind)让它更有趣)

ios - 转换以创建在 Apple 的相机应用程序中看到的桶形效果

ios - 实例方法几乎匹配可选需求