简体   繁体   中英

CoreData - Making Objects That May Or May Not Be Stored

I have an existing iOS project which I'm trying to change to use CoreData instead of Keyed Archiving. In my existing project, I often create objects when the user closes a modal view. Then I do some validation on that object, and if all is well I go ahead and store it. But if the object is determined to be invalid, I simply throw it away and throw up a validation message to the user.

I got nervous about this pattern when I started using Core Data. I didn't want to keep creating "temporary" objects in my database only to turn around and delete them. So instead I create the objects without assigning them to a NSManagedObjectContext. Then later when I determine things are valid, only then do I assign it to a context.

At last here's the question: Is this a valid approach? Are things commonly done this way? I'm worried as my use of managed objects gets more complicated, with more relationships between entities, that I may regret this choice. Am I unnecessarily making things harder for myself?

A common way to do this is to create a child conteit of the main context. You can create your objects in that context, and if you want to save the changes to the main context and then save the main context. If you don't want to keep the changes just throw away the child context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM