Core Data for iOS: A Core Data Primer
- Persisting Objects to Disk
- The Core Data Approach
- Examining the Xcode Core Data Templates
- Summary
In order to get the most out of Core Data, it's extremely important to have a firm understanding of its fundamental operations. Over the course of this chapter, you'll learn the key terms and features of the different parts of a Core Data-based application.
Before looking at the Core Data terms, though, take a moment to think about how you might work with persisted data in an application without using Core Data.
Persisting Objects to Disk
When you're working with data to be saved in an application, you typically have collections of objects, maybe held in arrays, sets or dictionaries, which need to be archived to disk. When it comes time to save the data, you might encode or serialize those objects ready to be saved into a binary file or, for small datasets, store them in a .plist file.
As an alternative to working with binary files, and before Core Data came to iOS, developers could also make direct use of SQLite, a simple and very lightweight database, available on iOS devices since the early versions of iPhone OS. When writing an application that made use of large collections of objects, it would make sense to store those items in a database, offering huge increases in speed when saving and fetching objects.
SQLite, as its name implies, is based around the Structured Query Language, or SQL. You talk to an SQL database by issuing commands to, for example, insert or select (fetch) data. If you only need a specific object from the database, you can issue a command to fetch just that object; you don't need to worry about the efficiency and performance issues with loading an entire binary file from disk just to get hold of a particular object.
In order to work with SQLite, however, you need to make heavy use of procedural C APIs, writing lengthy portions of code to handle data access. To save an object into a SQLite database, for example, you would need to write out a string containing an SQL INSERT statement, populate that string with the values held by the object's instance variables, convert the string to a C-string, before finally passing it to a C function.