I'd like to have the name field of a core data object be trimmed before it's saved to the context. My idea was to use the validation function for this. The following implementation works:
@objc
public func validateName(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws {
guard let trimmedValue = (value.pointee as? String)?.trimmingCharacters(in: .whitespaces) else {
return
}
if name != trimmedValue {
name = trimmedValue
}
}
Without the if statement which sets the name field only in case of a change, core data throws an exception because of a cycle.
Now I have to questions:
- Is the validation function the best way of doing this?
- The above code is quite verbose if you have multiple objects with fields that have to be trimmed. I've tried to create a function trimField with an inout variable value and moved the code for trimming, checking for a change and setting the inout variable. But when I call it from the validation function, an exception is thrown because of a cycle. So it seems that a function with inout parameter does set the field value to "dirty" even if it's not set explicitly. Are there any other options?