开发者

Using Core Data as a model when not all objects will be stored

开发者 https://www.devze.com 2023-01-11 02:21 出处:网络
I\'m working on an iPhone application that downloads data from a web server and I sometimes, but not always, want to cache the results of these downloads. The entity I\'m dealing with is an Event. Eve

I'm working on an iPhone application that downloads data from a web server and I sometimes, but not always, want to cache the results of these downloads. The entity I'm dealing with is an Event. Events appear in the UI in the following ways:

  • as the result of a location-based search
  • as the result of a keyword-based search
  • a list of favourite events

Only in the third case is it necessary (or desirable) to store the data in the local DB. In other words, I download an event, and only when the user decides to add it to their favourites does it get stored locally.

It may or may not help to know that the data I'm downloading is in JSON format.

I want to use a consistent model object to represent events, but sometimes they will be stored in the database and sometimes they won't. I don't want my view controllers to have to know or care where the objects come from, and they should be capable of displaying an Event that comes from the local cache, or from a download without any special code to handle either situation.

Can I, therefore, use NSManagedObject (or a subclass thereof) to represent an Event? If I don't, it seems to me that I'll be dealing with two model objects, one being my custom object, for downloaded and unstored Events, and the other being an NSManagedObject subclass for stored Events, both of which have the same properties, but which are fundamentally different things.

Or, is there a third option where I create some kind of decorator object (or protocol?) that knows how to proxy requests from my View Controllers to the underlying data, which will sometimes be an开发者_StackOverflow中文版 NSManagedObject and sometimes a dictionary generated from the JSON?

What's the recommended solution here?


Easiest solution is to create the NSManagedObject instances without a NSManagedObjectContext via the -initWithEntity:insertIntoManagedObjectContext: method on the NSManagedObject.

When you want to actually persist the object all you need to do is set the context on the entity and the save the context.

0

精彩评论

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