How to Use Cocoa Bindings and Core Data in a Mac App

This is a blog post by Andy Pereira, a software developer at USAA in San Antonio, TX, and freelance iOS and OS X developer. Lately we’re starting to write more Mac app development tutorials on raywenderlich.com, since it’s a natural “next step” for iOS developers to learn! In our previous tutorial series by Ernesto Garcia, […] By Andy Pereira.

Leave a rating/review
Save for later
Share

Learn how to use Cocoa Bindings in your Mac apps!

Learn how to use Cocoa Bindings in your Mac apps!

Learn how to use Cocoa Bindings in your Mac apps!

This is a blog post by Andy Pereira, a software developer at USAA in San Antonio, TX, and freelance iOS and OS X developer.

Lately we’re starting to write more Mac app development tutorials on raywenderlich.com, since it’s a natural “next step” for iOS developers to learn!

In our previous tutorial series by Ernesto Garcia, you learned how to create a very simple Mac app called “Scary Bugs” with a table view, images, and editing capabilities.

In this tutorial you’ll go a bit deeper, and will learn how to:

  • Use Core Data to save your Scary Bugs
  • Utilize an NSArrayController
  • Implement Cocoa Bindings
  • Transform values using NSValueTransformers

Before you get started on this tutorial, you’ll need to be familiar with the information in the tutorials below:

Okay — ready to dive into the depths of Mac development? Great! Time to get started! :]

An Introduction to Cocoa Bindings

Apple describes Cocoa Bindings as: “a collection of technologies that help you encapsulate data, and write less glue code”. “Glue code” is the code in your app that doesn’t actually perform any real function, but helps you out in sticky situations (pun fully intended) when you are trying to tie together sets of code that weren’t designed to interoperate.

For example, in the Scary Bugs app you’ve been working on, your goal has been to display the ScaryBugData’s title and rating properties in the text field and rating view in the right side of the window:

You don't need to write glue code to do this on the Mac, thanks to Cocoa Bindings!

In order to do this, so far you have written some “glue code” like this:

-(void)setDetailInfo:(ScaryBugDoc*)doc 
{
    NSString    *title = @"";
    NSImage     *image = nil;
    float rating=0.0;
    if( doc != nil )
    {
        title = doc.data.title;
        image = doc.fullImage;
        rating = doc.data.rating;
    }
    [self.bugTitleView setStringValue:title];
    [self.bugImageView setImage:image];
    [self.bugRating setRating:rating];
 
}

You’re probably used to doing this all the time as an iOS developer, but wouldn’t it be nice if you didn’t have to write that code at all? That’s exactly what Cocoa Bindings does for you!

Basically, Cocoa Bindings allows you to use the properties inspector to bind a UI control to a property on an object. Then the control will display the value of the property, and when you modify the value of the control it will update the value of the property.

A screenshot of Cocoa Bindings

This tutorial will give you hands on experience with how this works – you will convert the ScaryBugs project to use Cocoa Bindings and remove all need for the old “glue code!”

By the time you’re done, you’ll really start wishing iOS had this cool feature ;]

Behind the Scenes: KVO

You might wonder how this magic all works behind the scenes.

If you’ve ever used key-value coding and observing in iOS, you might have a good guess – and you’d be right!

Assume you have a class named “Person”, with an NSNumber property named “age”. One way of setting the property would be as follows:

[aPerson setAge:@26];

An alternative way of assigning the property would be:

aPerson.age = @26;

The key-value coding way of doing it would be like this:

[aPerson setValue:@26 forKey:@"age"];

In short, key-value coding allows you to set the value of a property by the name, or the key, of the property. Behind the scenes, Cocoa Bindings uses KVO to update the associated property when a UI control is edited.

In addition to key-value coding, Cocoa Bindings also uses key-value observing (KVO). KVO allows you to register observers for an object’s properties. The observer implements key-value observing as follows:

observeValueForKeyPath:ofObject:change:context:

So whenever a change to the observed property occurs, observeValueForKeyPath is called and passed several parameters, including the object value and the property key.

Cocoa Bindings uses this as well behind the scenes, so it knows to update the controls when the property changes.

If you are interested in learning more about how Cocoa Bindings works behind the scenes, check out these documents:

Getting Started

In this tutorial, you will continue on with the project from the previous tutorial series. However, there have been a few changes:

  • All of the methods and outlets that used to implement the “glue code” have been removed from the app, since you will not be needing those anymore!
  • This tutorial is going to use Core Data, so I’ve added a few Core Data related methods and properties into AppDelegate.m to make it easier to get started.
  • Converted the table view to be from view-based to cell-based, to keep the tutorial simpler, as I’ll explain later.

Go ahead and download the starter project and open it in Xcode. Build and run the app to make sure it runs – at this point you should just see a blank screen like this (and none of the buttons work):

Now get ready to start coding! :]

Bug Entity

Go to File/New/File…. Under OS X, click “Core Data”, and choose “Data Model”. Click “Next,” and name it ScaryBugsApp.xcdatamodeld.

Note: it’s important that you use the suggested names in this tutorial, so that the existing project code — and the tutorial explanation of the code — line up! :]

Note: it’s important that you use the suggested names in this tutorial, so that the existing project code — and the tutorial explanation of the code — line up! :]

Select ScaryBugsApp.xcdatamodeld. Click “Add Entity,” and name the Entity Bug.

You need to add three attributes to your Bug entity: name, rating, and imagePath. Under Attributes, click the “+” three times, each time naming the attribute as “name”, “rating”, and “imagePath”.

Set the Type of each attribute so that name and imagePath are both “String,” and rating is “Float”.

Select “rating”, and then select the Data Model inspector (the third tab on the top half of the right sidebar) in the utilities drawer. Under the Attribute section, you will see a subsection named “Validation.” For Minimum, enter 1; Maximum enter 5; and set Default to 1. Doing this will guarantee that a rating will never be a value other than 1 – 5.

Save your changes with Command-S, then select Editor/Create NSManagedObject Subclass:

If you’re asked what entities you would like to manage in the step above, select “Bug” and click “Next”. Finally, click “Create”.

Go ahead, build and run your application to make sure that everything is OK so far. You should not receive any warnings or errors, but if you do verify the following:

  • Check the name of the .xcdatamodeld file.
  • Check that each attribute has a type associated with it.

Everything look good? Okay, move on to working with the NSArrayController! :]

Contributors

Over 300 content creators. Join our team.