Xcode 3 Modelingtools
Xcode 3 Modelingtools
Modeling Tools
Xcode has three modeling tools to help you create Mac and iPhone applications. The class modeling tool lets you examine your projects classes, the members of each class, and any relationships between classes. The data modeling tool lets you create data structures visually without having to write code. The mapping tool lets you create a mapping model to migrate data from an older data model to a new one. The data modeling tool and the mapping tool require Core Data. If youre not using Core Data, you may want to skip this chapter and come back to it later.
Class Models
Xcodes class modeling tool is similar to the class browser. Both the class modeling tool and class browser let you examine your projects classes, view the members of each class, and see the inheritance relationships each class has. Why would you want to use the class modeling tool instead of the class browser? The class modeling tool has the following advantages: You have more control over what appears in a class model than what appears in the class browser. The class modeler draws a class diagram that lets people see your programs structure without having to look at source code. You can add comments that explain what each class does. You can track the changes you make to a class model in a version control system. Xcodes class models support Objective-C, C++, and Java programs, but some work is required to use them with Java programs in Xcode 3.2. The class modeling tool needs an Xcode project file. Most Xcode projects have a project file; it has the extension .xcodeproj. The Java projects that come with Xcode 3.2 do not have a project file so you cant add a class model to them. The solution for Java developers is to temporarily install Xcode 3.0 or 3.1 in a custom location. Copy the Java project templates to the location of your user templates, which in most cases is in the following location: /Library/Application Support/Developer/Shared/Xcode/Project Templates/GroupName 58
59
Where GroupName is the name you want to appear under User Templates on the left side of the New Project Assistant. Java would be a good group name. Read the section Creating Project Templates in Chapter 1, Xcode Projects, for more information on working with Xcodes project templates.
60
Class List
The class list shows all the classes in the model. For each class you can see what superclasses the class has and the kind of class it is. Most classes are of kind Class, which means theyre ordinary classes. Objective-C programs have two additional kinds of classes: categories and protocols. A category is a collection of methods to add to an existing class. A protocol is a collection of method declarations. These declarations are not part of a class. Any class can implement the methods in the protocol. Java has protocols as well, but Java calls them interfaces. If a class has a book icon in the far right column, that class has documentation you can look at. Double-clicking the book icon opens the documentation for that class in Xcodes documentation window. Cocoa and Java classes are the most likely to have documentation available. Member List
Class List
Selection Area
Class Diagram
Figure 3.1
Class model window
61
Member List
Selecting a class from the class list fills the member list with the classs members. The member list displays the following information for each member: An icon describing the type of member. Member functions have the letter M for method, and data members have the letter V for variable. The member name. The member kind: method, variable, or class. The members data type. The data type for methods is the data type the method returns. The members visibility: public, private, or protected. Whether or not the member has documentation. A book icon signifies that the member has documentation. Clicking the book icon displays the members documentation in Xcodes documentation window. Double-clicking a class member from the member list opens the classs header file.
Selection Area
Selecting a member from the member list fills the selection area with information about the member. If you select a method, the selection area tells you the name and data type of each argument the method takes.
Class Diagram
The class diagram, shown in Figure 3.2, contains the classes in the model and the relationships between them. A solid line connecting two classes indicates inheritance, with the line going from the subclass to the superclass. A solid line connecting a class and a category indicates the class that the category is a category of. A dashed line indicates a protocol (or interface for Java programs) implementation.
Figure 3.2
Class diagram
62
Each class in the diagram has three compartments: the class name, properties compartment, and operations compartment. The background color for the class name reflects the kind of class it is. Cocoa classes are gray. Your classes are light blue. Categories are green with the name of the category in parentheses. Protocols are red with the name of the protocol in angled brackets. Properties are the data members of the class, and operations are the methods. Initially Xcode shows the class name, properties compartment, and operations compartment, but leaves the classs properties and operations hidden. Click the disclosure triangles to show the properties and operations in their respective compartments. Choosing Design > Roll Up Compartments shows the class name only. Choosing Design > Roll Down Compartments restores the properties and operations compartments. When you move the mouse cursor over a class property or operation, an arrow appears next to the property or operation. Clicking the arrow opens either the header file (for properties) or the implementation file (for operations in your code). Clicking the arrow for a Cocoa class operation opens the header file. There are two ways to organize the classes in the diagram: hierarchically and force-directed. Hierarchical layout places parents at the top of the diagram with their children below. Forcedirected layout places classes that other classes reference in the center of the graph. A forcedirected graph takes longer to create. If you have a lot of classes in your class model, you should use the hierarchical layout. Choose Design > Automatic Layout to choose the layout.
Figure 3.3
Class model inspector
63
64
Adding Comments
Xcode class diagrams can have comments that provide an explanation of what a class does. Choose Design > Class Model > Add Comment to create a comment. Select the comment in the class diagram to enter text for the comment. To attach a comment to a class, use the line tool to draw a line from the class to the comment. The line tool is in the lower left corner of the class model window.
Data Models
Xcodes data modeling tool is much more powerful than the class modeling tool. You can actually model data with the data modeling tool, not just view the data. Use the data modeling tool to create your programs data visually instead of writing code. To use Xcodes data modeling tool, you must be using the Core Data framework. The Core Data framework is available in Mac OS X 10.4 and later and in iPhone OS 3.0 and later. Core Data is a huge topic, too large for me to cover in this book. Read the Core Data Programming Guide that comes with the Xcode documentation to learn more about Core Data. There are three terms you must know before you can model data: entities, attributes, and relationships. Entities are the basic building blocks of your data models. Entities consist of attributes and relationships. Attributes contain data. Relationships represent relationships to other objects. In programming terms, entities are your classes, attributes are your data members, and relationships are your methods.
65
Entity List
Selection Area
Diagram
Figure 3.4
Data model window
66
Entity List
The entity list contains the entities in the data model. For each entity the list tells you the entitys name, the class it belongs to, and whether or not the entity is abstract. The class an entity belongs to must be NSManagedObject or a subclass of NSManagedObject. Abstract entities are entities you dont create instances of in your program. They are meant to be inherited by other entities. Cocoas NSObject class is an example of an abstract entity. You dont create objects in your Cocoa programs, you create the entities that inherit from NSObject: windows, views, controls, etc.
Property List
Selecting an entity from the entity list fills the property list with the entitys properties. The property list tells you the propertys name and the kind of property it is: attribute or relationship.
Selection Area
Selecting a property from the property list fills the selection area with information about that property. For an attribute you can set its data type, minimum value, maximum value, and default value. For relationships you can specify the type of relationship and the relationships destination. In the upper right corner of the selection area are four buttons, which you can see in Figure 3.5. The buttons, running from left to right, are: General, which shows information about the selected property. The General view is the initial view for the selection area. User Info, which is used to create information dictionaries. Configurations, which is used to create collections of entities. Synchronization, which is used to synchronize your data with other applications and devices. Most of the time, youll be using the General button. Refer to the Setting Dictionary Entries section later in this chapter for more information about the User Info button. Refer to the Adding Configurations section later in this chapter for more information on the Configurations button. Refer to the Synchronizing Data Models section later in this chapter for more information on the Synchrhonization button.
Figure 3.5
67
Diagram
The diagram area, which you can see in Figure 3.6, shows the entities and their relationships to each other. Lines represent the relationships between entities. The arrow points to the destination. Lines with arrowheads on both ends indicate a bidirectional relationship. A line with a single arrowhead indicates a to-one relationship, which means there is only one destination object. A line with a double arrowhead indicates a to-many relationship, which means there can be multiple destination objects. Each entity in the diagram has at least three compartments: the entity name, attributes compartment, and relationships compartment. If an entity has fetched properties, there will be a fourth compartment for the fetched properties. Initially Xcode shows the class name, attributes compartment, and relationships compartment, but leaves the classs attributes and relationships hidden. Click the disclosure triangles to show the attributes and relationships in their respective compartments. Choosing Design > Roll Up Compartments shows the class name only. Choosing Design > Roll Down Compartments restores the attributes and relationships compartments.
Adding Entities
There are two ways to add an entity to the diagram. Choose Design > Data Model > Add Entity or click the + button in the entity list. After adding an entity, use the selection area to specify the following information about the entity: Its name. Its class. The class must be NSManagedObject or a subclass of NSManagedObject. The entitys parent. Whether or not the entity is abstract.
Figure 3.6
Diagram for data models
68
When youre starting out, giving each entity the class NSManagedObject keeps things simple. Later on you may want to give each entity its own class. Each of these classes will be subclasses of NSManagedObject. Abstract entities are never instantiated. They are meant to be parents of concrete entities.
Adding Attributes
To add attributes to an entity, select the entity from the diagram or the entity list. Choose Design > Data Model > Add Attribute or click the + button in the property list and choose Add Attribute from the menu that opens when you click the button. After adding an attribute, use the selection area to specify the attributes name and data type. You can also specify whether the attribute is optional and whether it is transient. If an attribute is not optional, it must have a value or you will get errors when the user tries to save the data to disk. Core Data automatically stores your data in a data file and retrieves the data from the data file. Transient attributes are not stored in the data file. An attribute can have the following data types: Undefined Integer 16 (16-bit integer) Integer 32 (32-bit integer) Integer 64 (64-bit integer) Decimal Double Float String Boolean Date Binary Data Transformable
Most of the data types correspond to Objective-C data types. The data types that require more explanation are Undefined, Binary Data, and Transformable. Transient attributes should have an undefined data type. Only transient attributes can have an undefined data type. Give an attribute a data type of binary data when the attribute is more complicated than the Objective-C data types, such as a data structure.
69
Attributes with a transformable data type are converted to and from instances of NSData. Suppose you have an attribute that stores some text you want to display in a text view. You want to display rich text and you want to take advantage of NSTextViews Attributed String binding. If you make the attribute a string, you wont be able to use the Attributed String binding. By making the attribute transformable, you can use the Attributed String binding and display rich text. When you specify the data type, what you can set depends on the data type you chose. For numerical and date attributes you can set the attributes minimum, maximum, and default values. For Boolean attributes you can set the default value. For a string you can set the minimum length, maximum length, default value, and a regular expression. Use a regular expression to constrain the values the string can have. If you were using a string attribute to store a number, such as a credit card number, you would use a regular expression to limit the attribute to storing the characters 09.
Adding Relationships
To add a relationship, select the line tool in the bottom left corner of the data model window. Use the line tool to draw a line from the source entity to the destination entity. You can also add a relationship by choosing Design > Data Model > Add Relationship or by clicking the + button in the property list and choosing Add Relationship. After adding the relationship, use the selection area to specify the details of the relationship. You can set the following properties for a relationship: Name. Optional. An optional relationship does not require a destination. Transient. Transient relationships are not stored in the data file Core Data uses to store your data. Destination. You shouldnt have to change the destination. Choosing No Destination Entity from the pop-up menu removes the relationship from the diagram. Inverse, which bidirectional relationships use. If you have a relationship from entity A to entity B, the inverse is the corresponding relationship from B to A. Most relationships should have an inverse relationship To-Many. When you have a to-many relationship, the destination can have more than one object. An example of a to-many relationship is a student enrolling in courses. A student can enroll in more than one course. Min and Max Counts let you set the minimum and maximum number of destination objects in the relationship. Delete rule. If you dont select the To-Many Relationship checkbox, the relationship is a one-to-one relationship. You cannot set the minimum and maximum counts for one-to-one relationships.
70
Delete rules determine what happens to the source and destination objects of a relationship when you delete the source object. There are four delete rules. No Action. Delete the source object but dont delete the destination objects. Nullify. Delete the source object. Do not delete destination objects, but set each destination objects inverse relationship to NULL. Cascade. Delete the source object and all destination objects. Deny. Do not allow the deletion if the source object has destination objects.
Editing Predicates
Predicates are the way you specify conditions when searching. Fetched properties and fetch requests use predicates. Select a fetch property or fetch request from the browser and click the Edit Predicate button to open the predicate builder. The predicate builder comes with one predicate for you. If you want to combine multiple conditions, click the + button to add a condition. There are two ways to create a predicate. The first way is to choose Expression from the left pop-up menu. The second pop-up menu disappears. Use the text field to enter the condition. The second way to create a predicate is to choose one of your attributes from the left popup menu. If youre editing a predicate for a fetched property and no attributes appear in the pop-up menu, make sure you choose a destination entity for the fetched property by using the Destination pop-up menu in the selection area.
71
The second pop-menu up contains conditions. The conditions depend on the attributes data type. Numerical attributes have mathematical conditions like greater than, less than, and equal. String attributes have additional conditions such as starts with, ends with, and contains. Use the text field to specify the value. Suppose you have an Employee entity with three attributes: first name, last name, and salary. You want to find the employees whose last names start with J and earn more than $50,000 a year. To create this predicate: 1. Choose Add AND from the left pop-up menu. Doing so will create two branches out of the predicate. 2. For the top branch, choose last name from the left pop-up menu. 3. For the top branch, choose starts with from the second pop-up menu. 4. For the top branch, enter J in the text field. 5. For the bottom branch, choose salary from the left pop-up menu. 6. Choose greater than from the second pop-up menu. 7. Enter 50000 in the text field. For more information on predicates, read Apples Predicate Programming Guide. It is part of the Mac OS X and iPhone documentation, which you can read in Xcode.
Adding Congurations
A conguration is a collection of entities. Configurations let you store entities in different Core Data stores. If Core Data didnt have configurations, you would be limited to one Core Data store that contains the entire data model. Configurations allow multiple stores. To create a configuration, select an entity from the diagram or the entity list. Click the configuration button in the selection area. The configuration button is the third button in the four button group at the top of the selection area. Click the + button to create a configuration.
72
After creating the configuration, the next step is to add entities to it. Select an entity and select the checkbox next to the configuration name to add the entity to the configuration.
73
Syncing an Entity
To sync an entity, select it from the entity list and click the Synchronization button in the selection area. The Synchronization button is the last button in the four button group at the top of the selection area. Make sure the Synchronize checkbox is selected. The last mandatory step is to specify a data class using the Data Class combo box. The data class takes the following form: com.CompanyName.AppName.EntityName If the entity inherits from another entity, choose the parent from the Parent pop-up menu. The Exclude From Data Change Alert checkbox determines what happens when the entitys data changes. If the checkbox is not selected, an alert opens when the entitys data changes. You should limit data change alerts to the most important entities.
Syncing a Property
To sync a property, select it from the property list and click the Synchronization button in the selection area. Make sure the Synchronize checkbox is selected. Selecting the Identity Property checkbox tells Core Data to use that property to identify the record. The Exclude From Data Change Alert checkbox works for properties like it does for entities. Deselect it if you want an alert to appear when the propertys value changes. Below the checkboxes are two pop-up menus that are used to automatically resolve conflicts during syncing. The Preferred Client Type menu determines what client Sync Services uses first for the syncing: There are four values:
74
Chapter 3: Modeling Tools App, which is your application. Device, which is the physical device, such as a laptop, cell phone, or iPod. Server, such as Apples Mobile Me. Peer, which is a peer to peer client.
The Preferred Record menu determines what record should be used for syncing. There are three values: Truth, which means use the record in the truth database. The truth database contains all the clients records. Client, which means use the record on the client. Last Modified, which means use the most recently modified record.
Mapping Models
Mapping models are used to migrate data from one version of a data model to another. They specify the transformations needed to migrate the data. Why would you use a mapping model? Suppose youve written version 1.0 of a Core Data application. Time has passed and you write version 2.0. In the process of writing version 2.0, you made changes to the data model. By using a mapping model, people who saved data using version 1.0 of your application will be able to load their data in version 2.0. If youre new to Xcodes modeling tools you wont be using mapping models right away because you have to create the initial data model first. When you need to make changes to the initial model, create a mapping model to migrate your data from the initial data model to the new model. Mapping models were introduced in Mac OS X 10.5. If you need to support Mac OS X 10.4, you cant use mapping models. All versions of iPhone OS that support Core Data also support mapping models so there is no reason you cant use mapping models for iPhone applications.
75
76
Chapter 3: Modeling Tools Adding entities, attributes, and relationships. Removing entities, attributes, and relationships. Renaming entities, attributes, and relationships. Making minor changes to an attributes data type, such as changing an attribute from a 16-bit integer to a 32-bit integer.
Entity Mappings
Below the top section are the other three sections. The left section is the Entity Mappings section. It has one listing for each entity in the source and destination data models. There are six columns of information. Error column, which will be blank if there are no errors. If there is an error, a red X appears in the column. Number. Mapping Name. If the entity appears in both models, the name will be EntityToEntity, where Entity is the name of the entity. Otherwise, it will be the name of the entity. Source, which is the entity name in the source data model. H, which is the version hash difference. If the entity is different in the source and destination models, there will be an asterisk in the column. Destination, which is the entity name in the destination data model.
Detail View
Figure 3.7
Mapping model window
77
If there are any errors in your entity mappings, fix them. The data migration wont work properly if your mapping model has errors.
Property Mappings
Next to the Entity Mappings section is the Property Mappings section. Selecting an entity fills the Property Mappings section with the entitys attributes and relationships. There are four columns of information. Error column. If there is an error, a red X appears in this column. T, which is the type of property. Attributes have type A, and relationships have type R. Name, which is the propertys name. Value Expression, which represents an expression in a predicate.
New properties have a blank value expression. Attributes in the source data model have the following value expression: $source.AttributeName Relationships in the source model have a value expression that looks similar to the following: FUNCTION($manager, destinationInstancesForEntityMapping Named:sourceInstances:,RelationshipNameTo RelationshipName, $source.RelationshipName) If there are any errors in your property mappings, fix them. The data migration wont work properly if your mapping model has errors.
Detail View
The entity mappings and property mapping sections show the mapping data. Use the detail view if you need to change the mapping data. The detail view is on the right side of the mapping model window. Changing Entity Mapping Data Select an entity from the Entity Mappings section to change the entitys mapping data. You can change the mappings name, source, destination, custom policy, and source fetch. The custom policy is the name of the class for the mapping. Its a subclass of NSEntityMigrationPolicy.
78
The source fetch determines how Core Data fetches the data from the source data model. There are two source fetch options: default and custom. If you choose the default source fetch, you can supply a filter predicate. A filter predicate is like the predicates you can create for fetched properties and fetch requests in a data model. If you choose a custom source fetch, you can supply a source expression. Changing Attribute Mapping Data If you select an attribute from the Property Mappings section, you can change the value expression. Changing a propertys value relationship is optional. Value expressions can be as complicated as you want to make them, but you should stick to simpler value expressions in the mapping model. If you need a complicated value expression to migrate an attribute, write code to handle the data migration. A value expression has the data type NSExpression. Read the NSExpression class reference for more detailed information on value expressions. The NSExpression class reference has a link to Apples Predicate Programming Guide, which is also helpful. Changing Relationship Mapping Data If you select a relationship, you can choose whether to auto generate a value expression or use a custom value expression. If you auto-generate the value expression, supply a key path and a mapping name. The key path is one of the relationships in the Property Mappings section. The mapping name is one of the mappings in the Entity Mappings section. If you use a custom value expression, enter the expression in the Value Expression text field. Value expressions can be as complicated as you want to make them, but you should stick to simpler value expressions in the mapping model. If you need a complicated value expression to migrate a relationship, write code to handle the data migration. Creating a User Dictionary Clicking the User Info tab in the detail view lets you create a dictionary of key/value pairs for a mapping. The information dictionary lets views and controllers access the information contained in the mapping.
79
80
Chapter 3: Modeling Tools NSMutableDictionary* migrationOptions; NSPersistentStoreCoordinator* newStore; [newStore addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:url options:migrationOptions error:error]