开发者

how to handle error when saving managedObjectContext?

开发者 https://www.devze.com 2023-02-15 11:13 出处:网络
What\'s the appr开发者_如何转开发opriate strategy for restoring to the existing persistent store if there\'s an error when doing a -[NSManagedObjectContext save:] ?

What's the appr开发者_如何转开发opriate strategy for restoring to the existing persistent store if there's an error when doing a -[NSManagedObjectContext save:] ?

-[NSManagedObjectContext rollback]?

Or should I save a copy of the store on the filesystem before attempting to save: and then, if there's an error, use -[NSPersistentStoreCoordinator setURL:forPersistentStore:] to set the store to the saved store?

Thanks for any pointers.

Gonzalo


When the save fails you (as the programmer) did something wrong.

I wrote some pretty complex Core-Data applications and never saw a failing save in production.

Make sure that the values users can enter can be saved without error.

This means if you have a not-optional relationship don't accept the "Done"-button until the user has selected an entity for this relationship. Or set a default relationship entity.
If you need a NSString in a special format validate that string before accepting it.

It's more convenient for the user too. If you tell him 10 minutes ago you did something wrong, thats why I will delete all your changes he will think WTF?. If you tell him The value you try to enter is not in the correct format. Please use xxxxx he will think Ok, let's change it.

And now after you made sure that a save never fails you can put [context rollback] in it, because you should never say never.
But before you do this you should ask the user if he wants to send you the error log. Because a save should never fail.


I believe, although I don't see it written explicitly in the docs, that if an error occurs during save then the save fails and the data store will remain unchanged. You could easily verify this by copying the data store, forcing some sort of error, and then comparing the store to the copy.


NSManagedContext save returns a BOOL, YES if successful, NO if not. That will tell you for sure whether the data store has actually been changed.

Another thing: Take a look at Apple's "Core Data Programming Guide: Persistent Store Features," under "Configuring a SQLite Store’s Save Behavior." They give a complete example of how to set up full sync options for the store, to ensure against data corruption due to some interruption during the save process.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号