开发者

Having persistent and non persistent objects of the same type with CoreData

I am currently working on an iPhone app which uses CoreData to save some Objects persistently.

To make my point clear I want to give you a short introduction into the scenario:

I have some Data which I query from the Int开发者_StackOverflow中文版ernet. I save this data in an object called MyData and use it where I need it. When the data is used I want to save it persistently so I save it to a MyManagedData object.

I really don't like this solution for saving data. Because I have two classes saving exactly the same data, but one is managed by CoreData.

Is there a way to instantiate managed objects without saving them automatically to CoreData? So I can just have MyManagedData objects and save just a bunch of them? How do you construct such things?

Greetings


One viable approach is to have two managed object contexts. You're already using a context for your main persisted data, so you could create a new context for your 'scratch' data which you never save.

There's a few articles out there on the subject, such as http://www.timisted.net/blog/archive/multiple-managed-object-contexts-with-core-data/.

I've been using InnerBand to help with CoreData. It's simplified my code quite a bit and not got in the way.

If you use InnerBand, creating a temporary context/store for storing transient entities (not saved) should just be a case of doing the following:

// note - not calling [CoreDataStore mainStore] here --
// we use that for persisted main data
self.temporaryStore = [CoreDataStore createStore]; 

// and then create temporary entities like so:
MyEntityClass *myEntity = [MyEntity createInStore:self.temporaryStore];

Obviously, you should never call [self.temporaryStore save], as it is for transient data only.

Note: I've not tried the above strategy myself yet, but I believe it to be workable.

N.B. on a related issue, I'm also using mogenerator which takes the pain out of generating entity classes (and prevents clobbering of custom code you may have added to your entities classes when you regenerate the entity classes).


The simplest solution is delete the managed objects you no longer want before you save the context. That way the context will only write the objects you want to retain to the persistent store.

However, I wouldn't bother. I would just tell the context to delete objects when they are no longer needed and not to worry about whether they were written to disk at any particular time or not. If you've got so little data that you can keep it all in memory at once then the overhead of writing those objects to disk just to delete them later will be trivial.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜