What are some advantages of using Core Data? (as opposed to plist) - iphone

I am relatively new to iOS and programming, and I made an app before, but it used a plist for storage, which I saved to the documents folder. Now, I am thinking about switching over to Core Data, but it looks a little complicated, and I'm not sure if it will work for what I want. I am going to have a bunch of data which I need to graph, so I'm not sure if Core Data is best for this, as it seems that I cannot create an array type in the .xcdatamodeld file. What are some other advantages of Core Data? Is it faster? Easier to use (once you set it up)?
Update: For anyone wondering, I finished the app, and it was totally worth it to learn how to use Core Data, and it was a lot less complicated that I originally thought. Doing it with plists would have been hell. The way they go about doing it seemed a little cryptic at first but if you just start using it you will get it. The relationships are really what is awesome about it.

A few advantages off the top of my head:
Much better memory management. With a plist you must load the entire thing into memory; with Core Data only the objects you're currently using need to be loaded. Also, once objects are loaded, they're normally placeholder "fault" objects whose property data doesn't load until you need it.
Related to the above, when you have changes, you can save only the changed objects, not the entire data set.
You can read/write your model objects directly instead of converting them to/from something like an NSDictionary.
Built-in sorting of objects when you fetch them from the data store.
Rich system of predicates for searching your data set for objects of interest.
Relationships between entities are handled directly, as properties on the related objects. With a plist you would need to do something like store an object ID for a relationship, and then look up the related object.
Optional automatic validation of property values.
Data models don't use arrays, but "to-many" relationships are modeled as sets.

It's a matter of what you're saving. For simple strings, arrays, dictionaries, it's fine to use a plist. For something more complicated (data, images, non-object information) or something with to-many relationships (think relationship between song to album, or photo to photographer), then something like a more robust solution might work better like SQLite.
CoreData is an objective-c-based wrapper around SQLite. If you think you might want to something more complicated, CoreData might be the way to go.
If you need a quick tutorial, I'd check out: http://www.raywenderlich.com/934/core-data-tutorial-getting-started
This got me going and allowed me to learn the basics the workings of CoreData.
Good luck!

Related

Populating Core Data with Plist in Swift

Working on an application that I want to check the plist store that the app will come shipped with and prepopulate core data with the objects from the plist. I think....I am looking for advice on this part of my application. As this is my first time coding and I have been learning Core Data/Persistence more recently I am not used to reading C++ or any of the code completely prior to Swift. I understand it somewhat but not enough to actually know the order of coding within swift.
That being said I created a plist file that contains an array of objects that each of those objects contains either strings or integers depending on the value that was necessary. Now in those objects I actually made a "serial" number as it were so that I could refer to specific objects easily or use it as a means to store that particular string and save only that so that it could be recalled from the plist. I have no idea whether I should actually upload all the objects to core data or just leave them in plist. Nor do I have any idea which way to begin this section of code.
From my basic understanding of plist and the fact that I saved the serial as a string I figured I could present the objects selected by storing the string alone to the core data model then have the core data model recall all objects from the plist that contain that serial and present it to the user. Basically any small sample coding in swift that can actually head me in the right direction would be a big help! Also is it faster to do it this way or would it be faster/better to upload the objects to core data on the first launch/updated lists? How would I go about this method if that was better? I spent the better half of the last few days trying to read through non swift code and haven't progressed enough I feel.
Sorry if this is n00bish I am self taught in swift and really trying to learn the best ways for all this as I have a lot of ideas that I wish to personally create/oversee!

Options for Caching Generic Object Lists for iPhone?

I have an app that connects to an API and retrieves a large number of small objects at a time. These objects are returned from json-framework as a heirarchy of NSDictionary, NSArray, etc. They are basic data types, and the primary structure of most of the api calls is a list of items(which could be hundreds of items long).
I will be displaying the data in a UITableView, but I don't want all the data in memory(as I could potentially eat it all up). I also don't want to hit up the api for the objects again, as they can be cached for a few hours without any problems.
I have thought of a couple of solutions, but I am eager to hear other options. I have thought of using Core Data in various ways, but I'd like to avoid having to create and maintain entities for each type of entity returned from the API. Using Core Data like this seems like overkill. I could use core data to store archived objects, though I worry about the archiving/de-archiving overhead.
I really want a generic store that can keep a list of objects cached, and then be able to retrieve arbitrary items from the list.
The factors that I care about:
Ease of maintenence. If the api changes or we add other objects, I don't want to have a lot of places in the code to change. Storing generic objects(NSCoding compliant) is ideal.
Performance. Caching and retrieval will all be happening while the user is interacting with the app(in the background), but I don't want to consume too many resources to make the app feel slow.
Are there any existing libraries that already exist for this purpose? What options am I missing? Maybe convince me that creating Core Data entities for each data type is actually a good idea for an object cache.
In case you haven't tried out the facebook/Three20 library, they have implemented a disc/memory cache and have used it as one of the fundamental layers inside their network module. I used three20 in my app but I never used this cache layer directly, so I'm not sure about the performance with it. Still, it's a nice thing to keep in mind.
Besides, the Enormego team has implemented a stand-alone photo viewer thing. And inside this photo viewer there is a nicely-working disc-memory cache. I'm not sure whether it has anything to do with the three20 cache. But I do believe it can cache generic objects other than just images. You can try it out by yourself.

When to use CoreData in iPhone development

I've been looking into creating a new application for iOS and after my last few apps I've been tempted to use CoreData (for benefits including saving and automatic undo/redo).
I've been a little confused when trying to implement the data-model I've been given fr the project though, since it seems that CoreData seems very much much closer to a database than a data model.
Should I be using CoreData for an application that doesn't generally fit the 'large amount of data/records' description I would generally use an SQL style database for?
If it helps, the app I'm designing will be a sort of document editor, so there will be a number of objects I will need to represent (there might be embedded images, graphs/charts, hyperlinks etc within the document) and I need to create this model from an xml description.
Most of these 'items' need to implement a set of interfaces (the model was created for a Java product; I'm having difficulties seeing how inheritance and abstract interfaces can apply to CoreData), and every example I've found so far seems to add base elements (like an NSDate or String) to a simple model.
Does this sound like a candidate for CoreData, or is CoreData more of a tool for implementing a database in an application? (i.e a library system/staff database).
consider CoreData as an option once you are able to properly write the majority of the code it will replace. so once you know how to properly serialize/deserialize, write undo/redo, KVO, copying, etc.
Should I be using CoreData for an
application that doesn't generally fit
the 'large amount of data/records'
description I would generally use an
SQL style database for?
CoreData isn't restricted to large databases (at all) - it will work well with small sets, and beyond databases (binary files and documents, direct in memory use of models).
your example could benefit from CoreData. it depends on the amount of custom code you need - sometimes it is just easier to write the code if you're just using CD objects as an interface generator, and your app uses a lot of custom code/objects. to be honest, i've never used CoreData in a shipping app - i always found reasons to migrate models to existing code before then (assuming CoreData was also used during development/modeling stages).
it's a nice framework, but it shouldn't be viewed as a 'magic object generator' that will solve most problems. first, you need to understand he technologies/patterns you intend to replace with it. there is a limited number of ideal uses for it. if you can't write the code the objects depend on, don't bother using CoreData. iow - don't consider it as a replacement for initial effort because there are certainly times when it is a good choice and a bad choice - but you can't make an objective answer for your context if you don't (truly) understand what it is capable of.
One of the purposes of Core Data is managing an object graph in memory. This certainly fits your application. It can then be persisted to disk easily. Using a tool such as mogenerator allows you to use Core Data to manage the object life cycle, graph and persistence, but add your custom protocols on top.
In short, yes, you can use Core Data for non-database uses, with a bit of work to conform to the model.

Is there any reason why someone would want to create an Core Data model programmatically?

I wonder in which cases it would be good to make an NSManagedObjectModel completely programmatically, with NSEntityDescription instances and all this stuff.
I'm that kind of person who prefers to code programmatically, rejecting Interface Builder. But when it comes to Core Data, I have a hard time figuring out why I should kill my time NOT using the nice Xcode Data Modeler tool.
And since data models are stuck to a given state (except when you want to do some ugly migration operations where thinks probably go wrong and users get mad, really mad), I see no big sense in a data model that's made programmatically for the purpose of changing it all the time.
Did I miss something?
I dont think you missed anything. The only reason I can see to create your model programatically would be if the objects you are modeling are themselves dynamic: you could for instance build a coredata entity (or graph of entities) in response to a web service which changed over time, or was selected by the user. However, I think if you had that or a similar use case, you wouldn't need to write this question (and you'd probably solve it a different way anyway)
So, if your application is dealing with resources that are dynamic, as #Andiih mentioned, then this programatic is the only way to do it. I don't know what my core data entities are until runtime, I don't know what the attributes are, or what the data looks like. So, I ask the server to give me the kinds of resources I should support and what their attributes look like. I build the model, the entities, the properties, the relationships - at runtime. I still want to use Core Data because I'm dealing with a lot of data and I need the benefit of efficient memory management with NSFetchedResultsController, etc. I can only do this programmatically.
The trouble is how to handle migration to try and preserve as much of the persistent store as possible, to reduce the size of the networked data payload after the model changes. Right now I blast the whole model and the persistent store if there's a conflict. I haven't yet figured out a way to create an .xcdatamodel from a programmatically generated model, thus I can't yet create a version mapping to do the migration.
Everything is a trade off. Basically, I think IB and the visual Core Data modeler are the right tool if you're building a simple application. You'll need to make the determination when your application becomes large/complex enough that you prefer to have direct control over all aspects of the code.
Regarding Interface Builder, if you have an application with a variety of complex interactions between view controllers, and multiple custom controls, I find code more appropriate.
For Core Data, the question is pretty much the same. Does your project have a defined scope? Can you foresee everything in that scope being done within the visual modeler? If so, it's probably fine. For other projects, where you may be asked to add features on an ongoing basis, perhaps it's better to spend a little more time writing it out so you have more flexibility later.
One other thing to consider, that doesn't get mentioned much, is it's MUCH harder to ask for help with IB or any hybrid visual design/code system. When something does go wrong, or you need help, it's way easier to post your code, than try to explain what's going on in a visual modeler.
In general, there's no reason to build the managed object model in code. There's nothing you can do in code that can't be done in the model editor. There are some fancy tricks you can do in code, however, to work with multiple models. For example, you can merge two models, establishing cross-model relationships between entities in those models at load time (see Cross-model relationships in NSManagedObjectModel from merged models?).
Regarding whether it's a good idea to code or use the graphical editor, I think the balance tips heavily towards the graphical editor in this case. Being able to verify the model by visual inspection instead of (rather convoluted) code is a win. The model can still be verified by unit test, if you desire.
I have one use case that might be valid, what if you load some data from the internet whether it is XML from an RSS Feed or WSDL response, then flatten those responses into a tabular from generating an in memory data table and finally mash it all up into a single coherent data model, then you can create the entities for those in memory data tables and create master/detail relationships. That's one case I think Core Data data model generated programmatically could become handy and a powerful feature.
I've changed models programmatically in unit tests. For example, I wrote a class that is designed to work with Core Data models that have a particular protocol attached. Instead of testing against a random implementation, I mutated the default model by adding one just in the unit tests programmatically, and tested against that test-only model.

ORM on iPhone. More simple than CoreData

The question is rather simple. I know that there is SQLite. There is Core Data also. But I need something in between. More object-oriented than SQLite API and simplier than Core Data.
Main points are:
I need access to stored entities only by id. No queries required.
I need to store items of a single type, it means that I can use only one table if I choose SQLite.
I want automatic object-relational conversion. Or object-storage if the storage is not relational.
I can use object archiving, but I have to implement things (NSArchiver).
But I want to write some kind of class and get persistence automatically. As it can be done with Hibernate/ActiveRecord/Core Data/etc.
Thanks.
Everything you've said you want here is completely compatible with Core Data. Apple's giving you a solution that meets your stated needs exactly, so why are you trying to avoid it?
Beyond BNRPersistence, which Alex points out, I don't think you're going to find anything that maintains object relationships, yet is simpler than Core Data on the Cocoa platforms. An object wrapper around SQLite like FMDB still requires you to manage relationships in your own code.
Maintaining relationships between objects is a non-trivial task, which is why you see so few of these frameworks out there. Core Data gets it right for many people, so there isn't that much motivation among developers to build an alternative to Apple's solution. BNRPersistence was created out of Aaron Hillegass' long-time frustration with certain aspects of Core Data, but many people (like me) are perfectly happy with the way Core Data does what it does.
You might also want to look at Core Resource, a newer framework that provides some wrappers around Core Data to make common tasks easier.
You might consider a non-Objective-C approach to serializing objects, just as XML or JSON, where you don't have to write serialization code, if you don't want to, because the framework does it for you. For example, put your objects into a key-value attribute pairing with NSDictionary (via a wrapper class or whatever) that points to another record's id key, and then encode the mess with json-framework's JSONRepresentation call. You'd probably need to do your own relationship integrity tests, but voila, instant relational database.
Take a look at BNRPersistence.