Home

mac geekery

Get your geek on.

Primary links

  • about
  • recent items
  • user blogs
  • contact
  • advertising

Core Data as a Cheap Database

  • Development
  • Core Data


Is there any trivial way to use Core Data? What is the most lightweight way to have a database on a Mac? If I wanted to write an app that needed db capabilities, what options do I have that don’t require the user to install mysql and set it up on their own?

Rahul Sinha




codepoet Core Data is easy enough non-programmers can handle a basic database with it.

No, really, it is.

Let’s go through a simple no-code project to log phone calls.

Install the Developer Tools

Do not use the CD that came with Mac OS X if it’s not version 2.1 (it’ll say on the disc). Get the current tools from the Apple Developer Connection website.

Create the Project in Xcode

Open up Xcode and in the File menu choose “New Project…”. From the resulting window you have a lot of choices but you really need to only concentrate on making the choice between “Core Data Application” and “Core Data Document-based Application”. To make the choice, decide if you want your program to be a single-document program like iTunes, iPhoto, or Stickies or if you want it to be able to create multiple documents that can be shared, but have to be opened to get to the last set of data you were using.

Once you decide, select it and click on Next and name the project and save it somewhere.

Create the Model

From within the project, expand the Models folder and click once on MyDocument.xcdatamodel. In the toolbar, click on Editor. This turns the redundant file listing on the right into a document editor for the model. It would help at this point to make the window a bit larger so you can see what you’re doing.

On the left of the three-pane top are the entities. An entity is akin to an object, but it’s not. I’ll not dwell on that here. Next to it is a listing of properties for that entity and then on the right we have the properties of the property. Below that is the graphical model so that it makes some kind of sense.

We’re going to make a program to just keep track of calls so we only need one entity: Call. In the left column, click on the Add button (+). The focus will shift to the right, to the Name field. Name this entity Call. With Call selected, click on the Add button in the properties list and choose Add Attribute. Back in the name field, call this one time and pick Date from the menu below it.

Do the same for the following items:

  • caller (string)
  • phoneNumber (string)
  • messageFor (string)
  • message (string)
  • requiresCallback (boolean)

Save. You’re done with the coding part.

No, really.

Create the Interface

Off to Interface Builder. In Xcode, expand Resources and open the proper NIB file for your project type. Application users open MainMenu.nib and Document users open MyDocument.nib (yes, even though you, too, have a MainMenu.nib). This will bring up Interface Builder.

Remove the default text that’s in your document and prepare for a really neat trick. Move the document window to one far side of the screen. Switch to Xcode and resize the window so that you can see the IB window you just moved. Select the data model if it’s not open in the editor and then option-click-drag the graphical representation of Call a little to one side so that your pointer changes to the Add pointer. Drag to the IB window and let go. IB will present an alert asking if you want to create an interface for one or many objects. We want many, so choose that.

Interface Builder then creates a basic data-entry interface complete with a working search field, a table already bound to your data and a detail interface below it. Note how it knew we had a boolean value and so made a checkbox for us? The date/time field also has a date formatter on it, so you can type in “today” or “next month” and it will find the right date for you. It accepts most any representation of date, so enter it however you want.

Build and Run

You’re done with this basic project now. If you save and run this program, it’ll work as you expect. There are some things to tweak in the program to customize it further (like making a custom extension to saved files) but that’s beyond the scope of this. For that, look at the other tutorials on Core Data programs, like the excellent how-to on Cocoa Dev Central

Things to Note

You’re programming. Really. It may not feel like it because of the simplicity of it all, but that’s real Cocoa code running under the wheels and you have to be a little careful at times.

  • Don’t change your model and try to use old files.
  • Don’t give the Debug version of the program to people – it won’t run. Change the build style in the Project Settings to Deployment and compile that one to give to other people.
  • Read up on programming in Objective-C and Cocoa a little if you want to add features to it, like actually doing something with the data.

Above all, though, enjoy your new two-step mini-database.

Advanced

So now that you’ve made the application, what can you do? Cocoa has a some options for you if you know how to actually write some code.

NSPredicate and NSFetchRequest offer you the ability to make custom queries of your data, much like any other database. It would be best to go over the Predicates Programming Guide first and learn how they work so that you know what you can do.

[series-info:center]



August 11, 2008 - 8:02am
Michael said

Would love to see a follow-up to this post. Maybe on how to ad viewing and storing of different/ALL data forms. Optimizing the data file for size, etc…

  • flag this
August 4, 2008 - 9:52am
Peter said

As far as I know, Core Data isn’t available in the iPhone OS. I’m using http://entropydb.googlecode.com/ for the iPhone and for the time being, I’m using it for desktop OS X apps as well.

  • flag this
August 12, 2007 - 7:54am
Brandon Koons said

I’m working on a simple database program largely because of this article. The only snag I’ve hit is that I want to create multiple fields that are populated by the same entity. Is this possible? Any help would be greatly appreciated.

  • flag this
November 3, 2005 - 6:42am
KenDRhyD said

I do not know how many have used it, but having a ‘framework’ for Cocoa that supported the same basic features as ADO.NET would be an incredibly powerful tool. I am not a big fan of MS software, but SQL Server, .NET and ADO are about the only things out of that company that I admire. I have worked with all of them extensively, and they are excellent tools.

There are times when one needs to be able to do much more than the relatively simple access defined in the two sample project discussed here. Perhaps I am missing something, but there are some relatively simple things that I simply cannot figure out. Most of these requirements are based on the processing required to manage a schedule and game results for a Little leagie baseball season (the comments would apply to managing most team sport schedules). 1. How can I import data from a file, parse it, and add it to my database? 2. Note that in the above, one input record may create three datanase records (visiting team, home team and the game itself). 3. Displaying, entering scores and saving the information is relatively simple, as shown in your examples. 4. How do I scan the contents of the [Games] table and generate [Standings] records in another table? I need to keep track of several statistics for each team (number of wins, ties and losses against each of the other teams, so this table is [TeamID, OpponentID, Wins, Ties, Losses, BonusPoints], where the bonus points are assigned based on varius rules to break ties in the standings. 5. The initial contents of the [Standings] table are generated with some standard (albeit complex) SQL, but the remainder requies several passes through the data. 6. I need to be able to make a pass through the data and generate an HTML file for inclusion on a web site so participants can see the results.

Very few of these issues were addressed in the two sample projects, and I have not been able to find information in the Apple documentation that assists me in answering the questions. Nor does there seem to be any generic framework/interface for accessing a SQL (relational) database directly. Yes, I could code to the C interface for MySQL or SQLite directly, but: that is not an object oriented approach (non-Cocoa) or even C++; and it requires custom coding for each database, making it hard to switch.

  • flag this
November 6, 2005 - 11:15pm
cmh said

Check out the Core Data documentation on Apple’s developer web site http://developer.apple.com to learn how you can use it from Cocoa. Another good resource is Apple’s Cocoa-Dev mailing list; you might try asking there how some of the participants would approach developing such an application.

The articles in this series are very obviously about how to use Core Data without writing any code. To do the kinds of things you describe above, you’ll have to write code – the point of Core Data is to make that code easier and more straightforward to write, and to take care of the tedious details for you while letting you concentrate on what’s unique about your application.

Just note that Core Data is not an SQL wrapper. It’s an object graph management and persistence framework. You don’t work in terms of tables, you work with graphs of interconnected objects and let Core Data handle the heavy lifting of loading, persistence, and change tracking for you. It’s a much more convenient way to develop application than by writing code to a thin wrapper around SQL statements.

  • flag this
October 24, 2005 - 10:41pm
aricart said

if you don't mind coding:

1) you can use plists to build simply small type databases (dictionaries, arrays, strings, numbers and blobs (nsdata) are all supported, and they all serialize without additional work. The caveat is that these need to be loaded into memory for you to access (very bad once you start getting into 100s of records).

2) you can also use Berkeley DB (see man dbopen, btree, etc) - which is also included with OS X since the beginning of time. It supports hashtables, btrees, record-number-based storage, and persistent queues. You simply create the storage structure (you can mix and match the types of storage,operations,etc on the same application). The library provides strict ACID transaction semantics, and supports concurrency. Note this is not an SQL database or a db server. Performance is fairly good too, but not as good on OS X vs. Linux/Solaris. Still we are talking around 500K->millions of records reading per second depending on your machine. 1/10th of that for writing, which is not too shabby (and you'd be hard press to improve using your own code). The other plus, is that these are fairly standard apis, and thus portable. And because they are standard, you can access these files using not only C, but perl and other scripting languages.

  • flag this
October 24, 2005 - 10:57pm
Adam Knight said
Adam Knight's picture

If you save using the SQLite database format with this programming style you can also use other tools with SQLite to get at the data. Similar performance, too.
—
cp

  • flag this
October 18, 2005 - 2:16pm
KenDRhyD said

The two database articles are very interesting, but they seem to indicate that CodeData can only be used for ‘class referencing’; that is, where the code treats each record as a class instance. This is fine, and works for a large number of cases.

I am having some difficulty determining how I can use this in a different project: a baseball season schedule. I have a list of teams, a schedule of games with game number, date and time, location, home and visiting team, game status, and scores. Game status may be one of Scheduled, Played (scores are in), Rain-Out, or Re-Scheduled. So far this it is not significantly different from the samples discussed, but there are some issues:

1. How do I force the games to be listed in a specific order?
2. How can I filter the list to show only the games where a specific team is at home?
3. How can I filter the list to show games where a specific team is involved?
4. I want to create another table, Standings, that counts the number of games played and awards points for wins, ties and losses; how can I do that and display the results?
5. I want to make a pass through the data and generate an HTML page that displays the schedule and the current results; how can I do that?
6. I also want to create a page (or a table on the same page) for the standings.

Can CodeData be used to execute generic queries and manipulate the contents of database tables without instantiating them as objects? I ahve been working with C#//ADO.Net for my “food on the table” work, and I have been very impressed with the DataSet/DataTable/DataColumn/DataRow classes )and of course the providers) — can CoreData do anythinf like that?

  • flag this
October 7, 2005 - 8:24am
hernan43 said

If you install the dev tools, sqlite3 will be instaled on your system. It is an excellent lightweight database. I love using it for small and even some medium sized projects. For more information see the sqlite homepage.

  • flag this
October 7, 2005 - 9:05am
Adam Knight said
Adam Knight's picture

The library is on the system even without the tools. And, actually, you can make this tool save to a SQLite database easily. In the Document method just choose “SQL” when saving. In the Application type, change the store type in the application controller implementation (search for “XML” and make it “SQL”).
—
cp

  • flag this
October 10, 2005 - 4:24pm
fsbraun said

I’m pretty impressed how simple it is to create a small app. Once you have changed the Core Data “driver” from XML to SQL (REALLY SIMPLE!), I suppose the Framework is actually generating SQL statements to store or retrieve data.

Can I use Core Data to access a Server SQL database like MySQL or PostgreSQL??

Thanks for any help!

- FB

  • flag this
October 10, 2005 - 4:28pm
Adam Knight said
Adam Knight's picture

Nope, it only uses its own format of SQLite store. Nothing else. :\
—
cp

  • flag this
October 7, 2005 - 9:41am
quidire said

So SQLlite is on every OS X installation even if one does not install Dev Tools?

Is there a performance difference? (I can imagine there would be)

-RS

  • flag this
October 13, 2005 - 5:38am
hernan43 said

My experience with sqlite3 has been a completely positive one. I fell in love with it so much that I completely replaced MySQL with Sqlite3 in places where I would use small to medium dbs to test or do proof of concept type things. I have even used it in some production stuff, and it really works very well. It is a good thing to check out at least.

http://www.sqlite.org

  • flag this
October 7, 2005 - 9:46am
Adam Knight said
Adam Knight's picture

It’s the same library with or without. With the devtools you just get the management binary, I believe.

It has to be on the system as Core Data and a few other things use it.
—
cp

  • flag this
Syndicate content

Navigation

  • Popular content

Today's popular content

  • How to remove Duplicate Application Names in Applications Folder and in the Open With Menu (328,727)
  • How To Hide Your Porn (23,257)
  • Basic Mac OS X Security (15,850)
  • View hidden files and folders in Finder. (12,311)
  • Nondestructively Resizing Volumes (12,200)
more

© 2005-2010 Adam Knight, unless otherwise indicated.