# AbstractTree

Table of Contents

1. Create the Project
2. Design the Data Model
3. Add Code to the Application Delegate
4. Build the User Interface
5. Mediator Attributes
6. Create IB Connections
7. Configure Bindings
8. Build and Run!

View Options*:

Implementation Details
Screenshots and Media

* You will still be able to show/hide individual sections of the content.

AbstractTree is a Cocoa sample application that demonstrates how to use Core Data and Bindings with NSTreeController. The data model is intentionally simple and abstract - you can extend it to any hierarchical model suitable for your problem domain. Likewise, the user interface is minimal - just an outline view and buttons for creating and removing nodes in the tree. In addition, the project shows how to implement drag and drop for managing parent-child relationships of the Core Data content.

This tutorial will cover each step necessary for creating the project. By default, many detailed sections are not displayed, but can be viewed by clicking links found in the document.

## Create the Project

Using Xcode, create a new Core Data Application project.

#### Step by step

1. Launch Xcode.
2. From the File menu, select New Project and scroll to "Core Data Application". screenshot
3. Click "Next".
4. Name the project appropriately.
5. Click "Finish".

Xcode will prepare a blank Core Data Application project for you.

#### Additional Documentation:

- Creating Projects

## Design the Data Model

AbstractTree's data model consists of a single entity, "Node", representing a generic tree node. Most importantly, nodes have a to-one "parent" relationship and a to-many "children" relationship. (Nodes also have a name, so that there's something to display in the UI of the application.) In a general sense, trees have several types of nodes - root nodes, container nodes, and leaf nodes. A root node is a node without a parent; containers have children; leaves have no children. A data model could represent a tree in many different ways - we're just keeping things simple in this sample. So, in AbstractTree, a root node is implicitly any node with a nil parent, and a leaf node is implicitly any node that has no children.

The children relationship is the key to NSTreeController functionality. AbstractTree has a single entity in its hierarchy, so this is not an issue, but if there are multiple entities in a hierarchy they must all have a common key for accessing children. Without a common key, NSTreeController will be unable to manage its content. The parent relationship is present for two reasons: (1) modeling inverse relationships is a strongly encouraged practice when using Core Data, and (2) we test the parent relationship to determine the root(s) of our tree in the UI.

#### Step-by-step

1. In your project, find the data model file and open it. screenshot
2. Create a new Entity and set its name to "Node". (This is case-sensitive!)
3. Add an attribute, set its Name to "name" and Type to "string". Give it a Default Value of "tree node".
4. Add a relationship. Name it "children", set the Destination to "Node", and make it a "To-Many Relationship". Also, make the Delete Rule "Cascade".
5. Add another relationship. Name it "parent", set the Destination to "Node", and set the Inverse to "children".

The data model for AbstractTree is complete. screenshot

#### Additional Documentation

- Data Modeling for Core Data
- Managed Object Models

## Add Code to the Application Delegate

The application delegate object provides the necessary Core Data support by loading the managed object model and creating the persistent store coordinator and managed object context objects. All of this is in boiler-plate code provided by the Xcode template - you don't have to do anything here, unless you wish to customize these actions for your application. For this project, we need to add some IBOutlets and implement some additional methods to manage drag and drop.

We need an outlet to the NSOutlineView so we can register it for receiving drag operations, and to the NSTreeController to use it as a mediator in the drag operation.

For drag and drop, we make the application delegate the data source of the NSOutlineView. This does not obligate us to implement the "standard" data source methods, because that functionality will be provided by binding to the NSTreeController. Instead, we simply implement the data source methods specific to drag operations. In the drag, we use a URL representation of the Core Data objects, a simple but clean way of uniquely specifying them ideal for pasteboard operations.

If you are following along with your own project, add the outlets to your application delegate and copy the source implementations found below the line "#pragma mark Code Added for AbstractTree Drag and Drop".

#### Step-by-step

The source code for AbstractTree_AppDelegate.m is the best step-by-step guide for this section. Look for the line "#pragma mark Code Added for AbstractTree Drag and Drop" - everything above that line is boilerplate generated when you create an Xcode project with the Core Data Application template. Everything below the pragma is specific to this project. Almost every line is commented, so it should be fairly easy to understand what is happening in the code - read the "Conceptual" section below for a discussion of how everything fits together. Also, be sure to check the header file (AbstractTree_AppDelegate.h) and note the additional Interface Builder outlets and actions that have been added. These additions are necessary for making the connections in IB.

#### Additional Documentation

- NSOutlineViewDataSource Protocol Reference
- Implementing Action Methods

## Build the User Interface

AbstractTree’s UI is minimal: it consists of a single window containing a NSOutlineView and two NSButtons. The outline view shows the nodes in the tree, hierarchically arranged, and the buttons allow you to create new nodes and remove existing nodes. Node names will be editable by double-clicking them directly in the tree. We will use a NSTreeController to mediate between the outline view, the buttons, and the data model for the tree.

#### Step-by-step

1. In your project, find MainMenu.nib and open it. screenshot
2. Add a NSTreeController to the nib. In Interface Builder 3, you add objects to a nib by dragging them from the Library panel. screenshot
3. Open the window object in the nib by double-clicking it.
4. Add a NSOutlineView and two NSButtons to the window. screenshot

#### Additional Documentation

- Interface Builder Workflow Tools

## Mediator Attributes

In MainMenu.nib, the NSTreeController needs to be configured. Set it to "Entity" Mode, with an Entity Name of "Node". In addition, the "Prepares Content" should be checked and the Fetch Predicate should be "parent == nil". This predicate will constrain the controller to objects which are root nodes because those nodes will not have any value for their parent relationship. It is also necessary to configure the Key Path for Children, which will be simply "children" - matching the name of the appropriate relationship in the data model. The Count and Leaf key paths can be left blank.

#### Step-by-step

1. In Interface Builder, find the document window for MainMenu.nib and select the NSTreeController. screenshot
2. Open the Attributes Inspector (from the Tools menu or ⌘1). screenshot
3. Set the Mode to "Entity"
4. Set the Entity Name to "Node"
5. Set Prepares Content
6. Set the Fetch Predicate to "parent == nil"
7. Set Key Paths:Children to "children"

#### Additional Documentation

- Changing Object Attributes
- Providing Controller Content

## Create IB Connections

We need to connect a number of outlets and actions in Interface Builder in order for messages to pass between the objects in the application. Some of these connections are already in place when the project is created, so we'll just focus on the ones you have to add. Specifically, the connections needed are:

- AbstractTree_AppDelegate's treeController outlet to NSTreeController object
- AbstractTree_AppDelegate's outlineView outlet to NSOutlineView object
- NSOutlineView object's dataSource outlet to AbstractTree_AppDelegate
- NSButton "Add" to NSTreeController addChild: action
- NSButton "Remove" to NSTreeController remove: action

#### Step-by-step

Interface Builder connections can be created several different ways. For a complete description, see the external documentation links below. One method is described here:

1. Press the "Control" key.
2. Click on the object that is the source of the connection. This is the object with the outlet, or that object that will connect to an action.
3. Drag the mouse to the destination object. This is the target of the outlet or object with the action. A blue connection line will appear during the drag. screenshot
4. Release the mouse button when the destination is reached. A panel showing the destination options will appear. Click the appropriate option to complete the connection. screenshot

#### Additional Documentation

- Creating and Managing Outlet and Action Connections (Interface Builder User Guide)
- Outlets (Cocoa Fundamentals Guide)

## Configure Bindings

Bindings are the final step in making the application come together. Two objects will be bound - the tree controller and the outline view's table column. The tree controller will bind its managedObjectContext to that of the application delegate. The table column will bind its value to the tree controller. The bindings are:

- NSTreeController.managedObjectContext -> AbstractTree_AppDelegate.managedObjectContext
- NSTableColumn.value -> NSTreeController.arrangedObjects.name

#### Step-by-step

1. In Interface Builder, select the NSTreeController.
2. Open the Bindings Inspector (from the Tools menu or ⌘4).
3. Bind the Managed Object Context to AbstractTree_AppDelegate.managedObjectContext. screenshot

#### Additional Documentation

- Configuring Cocoa Bindings (Interface Builder User Guide)
- What Are Cocoa Bindings? (Cocoa Bindings Programming Topics)
- Controller Key-Value Observing Compliance (Cocoa Bindings Programming Topics)

## Build and Run!

You should be able to build and run the project from Xcode now. Try the Add and Remove buttons, they should create and destroy nodes displayed in the outline. Double-clicking a node in the outline should allow you to edit its name. Dragging nodes in the outline should allow you to reorganize the node hierarchy.

Copyright © 2007 Apple Inc. All rights reserved.