Adding Core Data to iPhone app with existing (plain) models
I have a reasonably complex iPhone app that relies on an API to fetch data from a server and display it to the user. I have about 5 model classes that are used throughout the app - they simply extend NSObject.
I want to add some persistance to the models, to allow certain parts of the app to be used even if the device is offline - it really is basically just glorified caching. I only want certain instances of my models to be persisted - for example, items the user has bookmarked - and others should not, for example hundreds of search results.
Is Core Data the right solution for this? The difficulties I can see are:
I was hoping I could keep using my models throughout the app without changing the code that doesn't need to care about persistance, but that doesn't seem feasible given my requirements. The alternative is to set up a new set of Managed Objects in parallel to my existing objects, and only use the Managed Objects for persistance - but this kind of duplication never seems like the right solution.
Should I be trying to shoehorn Core Data into this, and if so, how? Or should I just be looking at other options - sqlite3 (seems a bit complicated for what I need), user defaults (probably not what they're intended for), or even serializing and writing my own objects to files (seems hack-ish).
Thanks for any input!
Why not take a look at NSKeyedArciver/Unarchiver? I would say that Core Data is the obvious solution when working with very large amounts of data along with sqlite databases, but NSKeyedArchiver is what I use to save models. Check out Apple's documentation here. Using NSKeyedArchiver is pretty simple IMO, and you can store pretty much anything you need with it.
Right now you instantiate data objects as subclasses of NSObject. You could use another level of indirection to choose whether to create an object as a subclass of ManagedObjectModel instead, and keep most of your app untouched using a protocol defining the interface you use to access information from those objects, then passing around objects of type id<DataObjectProtocol>
. Failure to fetch would be an indication of a non-local object.
Alternatively you could create everything as a managed object and just not store anything but a key for the data you don't want to store locally. Thus you can know if any object exists and how to fetch it if needed but you don't spend a lot of time or space persisting data that should remain in the cloud. The way to do this would be to define all but the key in the model as optional.
I would choose Core Data because of its flexibility, utility and optimisation. It really is worth learning. I would not recommend the sqlite3 approach, the way forward on iOS is Core Data. If you use some kind of file storage you should think about how to batch reads and/or writes since you could hit some bad performance issues doing multiple small file operations.
链接地址: http://www.djcxy.com/p/54210.html