iOS optimize

Gain a basic understanding of iOS Core Data

It is important to understand the benefits of the Core Data framework when it comes to using persistent data on iOS devices.

There are several options when it comes to using persistent data on iOS devices. It is important to understand the benefits of each approach before deciding which tactic to adopt. If a small amount of information - such as user and application preferences - is all that needs to persist between launches, the NSUserDefaults class is a good choice. Key-value pairs, dictionaries and arrays can all be stored as user application preferences using the NSUserDefaults class. Using a property list (.plist) approach is also a viable option for storing small amounts of data using a dictionary or array. The NSDictionary and NSArray classes support reading from and writing to a property list file. If the app requires more extensive data to be stored and retrieved on a regular basis - like a contacts, recipes, shopping lists, etc. - the Core Data framework will need to be used.

Using Core Data

One of the most powerful features of the iOS platform is the ease of integrating database features into an app. Many iOS apps use the built-in SQLite public-domain database engine - along with the Core Data framework - to persist information within their iOS apps. Using Core Data virtually eliminates the need to work directly with the database, therefore insulating the developer from writing transact SQL statements to manipulate the data. An iOS app will typically need to interact with only a few classes. The NSManagedObject class represents elements that get stored. Think of a managed object as a single record in a table. The NSManagedObjectContext class represents a collection of managed objects. The managed object context class handles creating, working with and saving managed objects.

Core Data managed objects are defined in a managed object model. The NSManagedObjectModel consists of entities, attributes, validations and relationships. While it sounds complicated, it is really quite simple. To add Core Data capabilities to an iOS app, you must include the framework (Figure A). Once the Core Data framework has been added, you will need to add a Core Data model file. Create a new file to be added to your project by either choosing File >> New from the menu, or by right clicking the project in the navigator pane and selecting 'New File'.  Choose the data model template and name the file (Figure B).

Figure A

Figure B

Once created, the data model file will appear in the navigation pane of your project. Double click the data model (.xcdatamodeld) file to open the editor window (Figure C).

Figure C

The data model editor will allow you to add entities, attributes and configure relationships among other things. Think of entities as tables and attributes as fields within these tables. Choose 'Add Entity' from the bottom of the data model editor window. A new entity object should appear under the list of entities (Figure D).

Figure D

Give the entity a name that best represents the collection of data that will be captured and stored. For example, if you were developing an iOS app for storing information about various wines in your collection, you might name the entity 'Wines.'

With the entity selected, add an attribute to store each specific piece of information to be contained within the entity. In other words, if we are storing information about our favorite wines, we might need to create attributes to represent the name of the wine, vintage, type, number of bottles on hand and a score or rating. Add attributes by clicking 'Add Attribute' at the bottom of the data model editor window. Each attribute must be assigned one of the following Core Data supported types (Table A).

Table A

Data Types

Objective-C Storage

Integer 16 NSNumber
Integer 32 NSNumber
Integer 64 NSNumber
Decimal NSNumber
Double NSNumber
Float NSNumber
String NSString
Boolean NSNumber
Date NSDate
Binary Data NSData
Transformable User defined

Depending on the complexity of information stored, it may be necessary to create several entities with defined relationships. From a database programmer's perspective, this approach is known as normalization. Normalization helps with performance when searching, filtering and sorting large datasets.

Managed objects can be considered dictionaries with a known set of keys. Attributes for managed objects can be accessed using the valueForKey accessor method. Using the wine list example, we can access individual attributes from the Wine entity as follows:

NSString *wineName = {myWine valueForKey:@"wineName"};

Updating attributes can be accomplished by using setValue:forKey:

[myWine setValue:@"Silver Oak" forKey:@"wineName"};

There are four main classes in the Core Data environment that are used to manipulate managed objects. These classes include: NSManagedObjectModel, NSManagedObjectContext, NSPersistentStoreCoordinator and NSPersistentStore. The Managed Object Model and Managed Object Context classes mentioned earlier are where all interaction with the data happens. The Persistent Store Coordinator and Persistent Store classes interact with the actual SQLite or binary storage file. There is no reason to interact directly with the data file(s).

Where to go from here

It is impossible to describe all of the features, functions and uses of Core Data in half a dozen paragraphs. In typical Apple fashion, however, the Core Data environment creates a layer of classes between the developer and the iOS. This not only allows for quick development and deployment, but also guarantees compatibility with future releases of iOS. There are several good references and tutorials to help you immerse yourself into Core Data development. The Apple Developer site's Core Data Basics documentation is a great starting point. Apple also provides a Core Data Tutorial for iOS to help developers get started.

For the data adventurous, the SQLite Manager plug-in for Firefox is a great tool to assist in creating proof-of-concept databases. While the Core Data environment does not allow the use of externally created SQLite databases, you can use the mock-up design as a model for recreating the data structure within the XCode data-modeling interface. With a basic understanding of Core Data, you can develop iOS apps comparable to Apple's Contacts and Notes apps.

About

Gregory Dean is the CTO for the Wilen Group. He has spent the past 25 years in C-level positions setting the tone and direction of technology-driven services organizations. Gregory is constantly researching technologies and developing capabilities to...

1 comments
atoms
atoms

It is not correct to say that " If the app requires more extensive data to be stored and retrieved on a regular basis - like a contacts, recipes, shopping lists, etc. - the Core Data framework will need to be used." SQLite databases can be used directly giving you all the power of a relational database without all the overhead of Core Data. I'm not saying that Core Data doesn't provide a lot of advantages, but every situation is different and there are going to be apps that fall in between the simple needs for plists or UserDefaults and the more complex capabilities of Core Data