1
votes
  1. I have set up Core Data stack with some validations for entity properties;
  2. Store some managed objects to sqlite file;
  3. Manually corrupt managed object data in the sqlite file so they would fail to validate with validation predicates.

However I can still the fetch objects with invalid values after that.

My question is whether it possible to validate the sqlite file so I that ensure I am fetching managed object with valid values?

I know that addPersistentStoreWithType:configuration:URL:options:error: check for schema integrity, but I would like to check whether stored data validates with model.

1
As far as I know, validation is applied to objects in the managed object context and is checked when the context is saved (or a validate method is called explicitly). I do not think that validation is done when loading from the persistent store file. - Martin R
@MartinR I could validate after fetch, but I tough I might have missed something and there is cleared way to do this without the need to fetch/validate manually. - Kirsteins
How are you "manually corrupting" the data? Like @MartinR says, Core Data's validation scheme applies when saving data. Are you editing the SQLite file outside your app? - Tom Harrington
@TomHarrington Yes, I am using sqlite3 utility, but that is only to check how Core Data works with store that has some invalid data. I need this validation to work with sqlite file provided by user. There is NSValidateXMLStoreOption for XML, but there is nothing for sqlite as far as I know. - Kirsteins

1 Answers

2
votes

Core Data does not support automatic validation of data when fetching it. The built-in validation scheme applies only when saving changes or when you specifically request it. Managed objects must pass their entity's validation rules or saving fails.

If you need to validate values when you fetch them, you need to write your own validation code. There are methods on NSManagedObject that perform validation on request-- validateForUpdate: and similar methods to check the entire object are likely what you'll need.

It's true, as you mention in a comment, that there's a flag named NSValidateXMLStoreOption, but that only checks an XML store against its DTD. It makes sure you have valid XML, but it does not imply running Core Data validation checks.