AnthonyMDev
AnthonyMDev

Reputation: 1506

Core Data - Delete Object if failing validation before save

I have an NSManagedObject that, when I save my NSManagedObjectContext, I would like to delete itself if it fails validation, rather than just stopping my context from saving and throwing an error. This way my save can continue successfully.

I'd only like for this to happen during a save. I'm not sure if validateForUpdate() is the right place to do this. Is there an accepted convention for how to do this?

Upvotes: 1

Views: 391

Answers (1)

Marcus S. Zarra
Marcus S. Zarra

Reputation: 46718

First, you are better off validating the data either in the UI or in the network layer rather than relying on the persistence layer to do the validation. That will avoid this issue completely.

Having said that, you can run -validateForUpdate and -validateForInsert to insure that the object is valid before you call save.

You can also let the error fire and then unroll the error to find out which objects are invalid, delete them and then save again.

Both of those solutions are sloppy compared to properly validating the data before the save (UI or network layer).

Upvotes: 3

Related Questions