1

I'm writing to CoreData with key-values:

entity.setValue(value: <Any?>, forKey: <String>)

Before writing to CoreData I store the value and the field name in vars:

var value: Any?
var field: String

I would like to do a simple validation before I attempt to write to CoreData. The function validateValue(_:forKey:) seems to satisfy my needs but I don't understand how to use it:

try entity.validateValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey: String)

In my case it would be like:

    do {
        try entity.validateValue(value, forKey: field)
    } catch {
        let validationError = error as NSError
        print(validationError)
    }

But how do I pass

var value: Any

to

AutoreleasingUnsafeMutablePointer<AnyObject?>

Is it even possible to use the validateValue function in this context?

Thanks!

  • Why are you using setValue(forKey:) instead of accessing the properties of your model class directly? `entity.someValue = 42` instead of `entity.setValue(42, forKey: "someValue")` – Joakim Danielson Aug 17 '20 at 11:06
  • I have a pretty complex input model and the key-value approach would save me a lot of duplicate coding. =) – learningbydoing Aug 17 '20 at 11:19
  • And using `Any` instead of the actual type of the value will make it less complex? Anyway, have you looked into overriding validateForInsert/validateForUpdate instead? – Joakim Danielson Aug 17 '20 at 11:37
  • Well, you just have to trust me on that. :) Yes, I have Iooked into validateForInsert/Update too but since I want to validate the inputs individually, validateValue seems like a more suitable choice. – learningbydoing Aug 17 '20 at 11:46

1 Answers1

0

You should be able to do let pointer = AutoreleasingUnsafeMutablePointer<AnyObject?>(&value).

You should read the docs of validateValue here to ensure you are using it correctly (e.g. implementing validate<Key>:error:)

vrwim
  • 13,020
  • 13
  • 63
  • 118
  • Thanks for your reply but unfortunately this gives me the dreaded "Thread 1: EXC_BAD_ACCESS (code=1, address=0x6e617041)" error. I edited my question with a snippet of error handling. Does it look correct? – learningbydoing Aug 17 '20 at 11:22