iOS Core Data: Confused about Core Data and database - iphone

I am really confused on what the Core Data actually is. Or I guess my question is, when dealing with a database, would you use Core Data? Like if I wanted access values from a database would I be using Core Data to access those values? How would I approach this problem?
Thank you so much for the help.

Core Data is an framework that does the work of "object persistence". In other words, it's code you can use that takes care of saving a collection of objects to disk and loading them again later. It does a lot of work to allow you to store lots of data and load only the objects you need at a time, and unload ones when memory is tight.
Core Data can use a database to accomplish this, but that's it's business, not yours. When you use Core Data, it is a black box. You tell it to save the data and then step out of the way.
If you want to interact with an existing database, such as a MySQL database on a web server, that's a completely different matter. You might use Core Data to store local copies of objects on your device, but in that case Core Data won't care that the objects are copies from some other database. It doesn't care.

It is a convenient, native means of storing data in your iOS applications. Don't think of it as sqlite although you can view the files it creates with various sqlite tools. Instead think of it as a tool for manipulating an object graph of information important to your app.
I've used it in two main ways. First to store a bunch of static data that is important to an app, in one case that was a large amount of location data for an indoor mapping application. What arrived as a massive CSV file of waypoints was converted to core data. Core Data was incredibly useful for this because it allowed preparing a sqlite file which was shipped with the application containing all the infomation. Updates from a web service arrive as more CSV that is added to the Core Data to keep information current. At runtime the location information object (the waypoint a user is at) is retrieved with a predicate (i.e. the point they tapped on) and that object, through its Core Data relationships, indicates where it is possible to go from that point. Core Data provided the information necessary to perform A* routing through the indoor map.
Second it is great when you have a bunch of objects arriving as JSON and you want to be able to store and access those objects later. Let's say you have a typical app where you have a User and some information about the User, let's call it Thing. Users have Things. When you want to know something about a User you retrieve the Core Data record using a predicate - typically "name" or similar - and you get all the information you stored about the User back. Again you can make use of relationships to explore the user's connections and make displaying information easy. Perhaps the User has many Things, then you can say "user.things" and you get a NSSet of NSManagedObjects representing those Things.
You use it like a database. Its utility is that it is easy to access from anywhere in your iOS code, it is easy to store and easy to retrieve information also. Faulting lets you retrieve one object and navigate to any object connected through relationships by following the relationships. Because you define the attributes and relationships yourself in the data model editor it is easily customized for what you need to store. To me it is one of the most used and most useful parts of iOS.
When you want to automate display of information from Core Data you can use a NSFetchedResultsController to initiate a fetch and to respond through delegate methods to changes to the underlying data. If you set up a UITableView to use a NSFetchedResultsController as data source, you can have the table automatically update whenever the objects displayed in the cells changed. Very useful for apps where you periodically update information and want what is displayed to be kept current.
When your object model changes it is possible to maintain all of your existing information and migrate it to the new model. Core Data manages automatic (lightweight migration) when it can, or if you have made more radical changes you can supply rules to handle the migration.
The limitation of Core Data is that it is not great for storing binaries. If you have images that you need to store, far better to store a path to the location of the image than trying to store the actual data.

Yes, if you want a local database on your device, Core Data is the appropriate technology. It probably makes sense to start your research with the Core Data Programming Guide.
You can alternatively use SQLite (which Core Data uses in the backend), but Core Data offers some material advantages and is the preferred database interface for iOS. If you decide to pursue SQLite for any reason, though, I'd suggest you contemplate using the FMDB Objective-C SQLite wrapper.
But Core Data is generally the way to go.

Related

Use txt files or sqlite with core data in project?

I am developing iPhone app for a web application currently running online. Current web application is big and complex and uses SQL to store vital information like member details, login credentials etx. Other stuffs like info about several sections, groups, sub groups and other information related to each are saved in txt. Current system uses its own standard to keep data in files and also made custom algorithm to read and write data in it. Each txt file is below 1 mb size. There are lot of data manipulations going on.
Custom algorithm created just read those files and put all data in cache as records (same as in core data managedobjectcontext) and whenever there is a change in data the whole file is overwritten.
So while implementing the same what I want to choose for iPhone app? In apple website they said that 'SQLite is perfect for low-level relational database work' https://developer.apple.com/technologies/ios/data-management.html But in my case it is high level.
So please help me to make a decision. Do I want to manage data in files or sqlite database using core data?
I would also like to know whether it is possible to import those classes and algorithms currently in webserver to iOS, so I don't want to rewrite the same algorithm for iOS? Current server codes are in C#
In the rare case that you need to do low-level relational database work use SQLite. In the 99% other cases use Core Data. Don't ever store relational stuff into txt files. It'll just be a pain.
Your use case sounds like a good match for Core Data.
Often misunderstood, Core Data is an object store that happens to use sqlite for persistence. You don't manipulate the sqlite underneath it, Core Data manage the sqlite for you. You do not write SQL. The closest match to it in .NET is EDM and the Entity Framework in ADO.NET.
Assuming the classes and algorithm you want to import in the webserver is in C#, sadly those needed to be ported to Obj-C.

Is it better to create persistent stores, or use fixed files for data?

I'm prototyping a simple sports sim game for iPhone which will use Core data.
One the biggest challenges I'm facing is how to get the data into Core data in the first place.
The second biggest challenge is whether I should use core data's persistent stores or use fixed files (JSON) for pre-fixed game data.
--
Concept
The general concept is that a player can start a new game or continue an existing one.
When they start new game they would use pre-fixed data. (IE. A database which is read-only.)
When they continue game they would use a different database (the game database).
I am not sure how to deliver such a feature.
--
Prototype
Currently, I am experimenting with this prototype:
PHP Web App -> 2. API -> 3. iPhone
A local PHP web app which acts as a CMS.
A basic API which lets me expose specific data in a JSON format.
Read the JSON into Core Data using TouchJSON/other tools.
I have no intention of making the API public/online (for various reasons), so the method I have described is a only meant to ever be a one-way process.
This will of course cause a problem because I need to make the data read-only.
--
In sports sim games you will often find them using fixed files (.txt, .csv, .dat, etc) and then they read this data into memory or a database.
Therefore, using this concept I could:
Save the JSON as fixed files and read them at run-time into memory/core data.
And then whenever the player starts a new game, the existing core data store will simply be wiped.
However, having said that I've heard that you can use persistent stores as a method to overcome this problem.
Therefore I was thinking of setting up 2 persistent stores;
1) A pre-fixed read-only persistent store
2) The actual game store (which gets overwritten if you start a new game).
But which is better?
Creating JSON fixed files for consumption, or using 2 persistent stores?
I apologize if my question/concept is overly complex; but would welcome better/simpler solutions where possible.
I think you can use Core Data for applications that is going to store data on it and the database is empty when it starts but if you needed you data store to be pre-populated with data it is better to load it from fixed data like sqlite or xml files.

Core data migration with custom NSEntityMigrationPolicy - efficiency?

My iPhone app's core data model is changing and I have a custom mapping model and an NSEntityMigrationPolicy for one of my objects. However, I am worried that some of my users will have thousands of objects in their core data base, are there any best practices for either making the migration as efficient as possible, or conveying to the user what's going on when they load the new update which will try to migrate their data?
You need to warn the user that the app needs to update the data store and you should probably provide a "working" dialog so it doesn't look like the app has hung.
However, the migration is very efficient because it's really just changing the mapping on the store. It doesn't have to actual instantiate all the existing managed objects, it just changes the field names in the store. That can get complex itself in rare cases but most of the time it's barely noticeable.

Relationships between static application data and updatable user data with Core Data

I am developing an iPhone application that has a large database of items which the user can mark as favorite or add to certain lists.
Currently, the SQLite file is first copied from the bundle to the document directory to make it writable and used as a Core Data persistent store. However, I will run into problems when I need to deploy an application update down the track to add extra data or fix minor errors, where the user data will be lost or the application data needs to be synchronised.
After some research I found that perhaps I could add the application data as a read-only persistent store in the bundle and add a second writable persistent store to the documents directory for user data - Core Data would combine the data for me. But then I came across this in the documentation:
When you add stores, you specify the different store attributes by
configuration. When you are creating your configurations, though, remember
that you cannot create cross-store relationships.
I presume that means that I will not be able to maintain relationships between items and lists or items and a 'favorite' record. I guess I could go to the extra effort of traversing the relationship manually. Has anyone had experience with this?
Core Data provides an architecture to support versioning of managed object models and migration of data from one version to another. If your changes to the model are pretty simple, you can use "lightweight migrations", which are pretty easy.
Read more in Apple's documentation here: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreDataVersioning/Introduction/Introduction.html

New to Core Data for iphone

I am new to the iphone platform and am creating an app that retrievals a rss feed and displays it in a UITableView. I have gotten this working perfectly (or rather, the way I wanted). What I was thinking was I would store the current feed items on the phone so that it would initally load the old items it has stored while it got the new feed, then parse the new feed and add the new items and refresh the TableView. I was going to use Core Data to store it the old feed items because it would be a good way of learning Core Data and it would be an appropriate use of Core Data. However, I am having a difficult time learning how to use Core Data and connecting it with the Table/Array.
I have already googled and looked on stackoverflow for tutorials but have yet to find anything that explains it in a way I really understand. Any explanation of the overall steps that it takes to add Core Data to an existing app would be greatly appreciated. Full-blown detail are not necessary (but would also be useful). I'm just not very experienced with SQL or storing of data in such a manner and am having trouble wrapping my head around how the whole concept of Core Data works and how it connects to everything.
Also, any better method of doing what I'm trying to accomplish would also be appreciated.
There exist Xcode templates for Core Data-based applications; these are a great start to getting Core Data off the ground. However, it sounds like you want to integrate Core Data into your existing app, so you'll need to...
Add three main Core Data objects: the managed object context (MOC), the managed object model (MOM), and the persistent store coordinator (PSC). These need to be accessible wherever you want Core Data available, so either in your app delegate or, more preferably, in the controller or data source for your table view.
Create a MOM in Xcode. This will be a file of type .xcdatamodel, and it's an object graph that defines all the Core Data entities you want in your app.
Use NSFetchedResultsController (as suggested by Louis Gerbarg) to get data out of Core Data and display it into your table view.
Add code in your existing RSS-fetching-and-parsing routines to store new Core Data objects back into the store, when appropriate.
A good way to start is just to create a new Core Data application and play around with it a bit; you can also look at Apple's fantastic resources on the subject, like the Core Data Programming Guide and the sample apps Recipes and Locations. (Developer registration may be required.)
One last thing to note is that for the most part, a lot of the Core Data code you need to add can be ripped straight out of one of the Xcode template apps and pasted into your program (this holds especially true for the accessors for the three Core Data objects you need). Be careful not to use code you don't understand, though.
If you are using CoreData to populate a UITableView you really want to use NSFetchedResultsController as opposed to trying to populate and sync array yourself. The documentation for NSFetchedResultsController includes links to several CoreData tutorials, including onces that populate table views.
NSFetchedResultsController is still a bit buggy and requires fragile workarounds. I would start with the simpler iPhone Core Data "location" tutorial before moving on to the Books tutorial.
Also, any better method of doing what I'm trying to accomplish would also be appreciate
yes, it sounds like Core Data might be overkill for your application. Assuming your feed items are stored in a collection object you can easily use OSX's built in serializaition.
Been noted in other Stack-Overflow posts, but I can highly recommend the Prag Prog book "Core Data: Apple's API for Persisting Data on Mac OS X" - most is also relevant to iPhone Core Data apps; there is a whole chapter on creating an iPhone app too.
http://pragprog.com/titles/mzcd/core-data