334 ❘ CHAPTER 15 DATA MODELING 1 5. Add the following code to your application ’ s data store setup: NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; 16. Pass the newly created options object in the - addPersistentStoreWithType: configuration:URL:options:error: message during startup. Your application is now ready to run. When it starts, Core Data detects that your current data model does not agree with the structure of your existing store. It automatically fi nds the older version of the data schema that does, fi nds the mapping that maps between those two models, applies the mapping, and updates your data store. CREATING NSMANAGEDOBJECT SUBCLASSES The beginning of this chapter mentioned that the entities you defi ne in your data model exist as instances of NSManagedObject at run time. Quite often, NSManagedObject is more than suffi cient for your needs. You might, however, need a class with more specialized functionality for many reasons: Localized business logic in the entity object Specialized or complex validation Custom pre - or post - processing of attribute changes Non - standard attribute types There are also a number of reasons why you wouldn ’ t need to subclass NSManagedObject: Provide attribute property storage Use any of the built - in Core Data property features Inherit properties from other entities Use Key Value Coding, Key Value Observing, or Bindings An NSManagedObject reads a description of its entity and dynamically synthesizes real Objective - C accessor methods at run time. The result is an object that, for all intents and purposes, is identical to a custom class that defi nes those properties in code. As an example, an NSManagedObject for an entity that defi nes a string name attribute property would be functionally identical to a custom class that implemented accessors compatible with a @property NSString* name directive. You can send either object - name and - setName: messages, watch for changes using Key Value Observing, and so on. Ask yourself if you really need to subclass NSManagedObject before continuing. To create a custom implementation class for an entity, start by subclassing NSManagedObject. You cannot use just any arbitrary class; your class must be a subclass of NSManagedObject. The easiest way to get started is to use the Managed Object Class fi le template. This template appears only ➤ ➤ ➤ ➤ ➤ ➤ ➤ ➤ c15.indd 334c15.indd 334 1/21/10 3:52:42 PM1/21/10 3:52:42 PM Download at getcoolebook.com when you have a data model open and (optionally) one or more entities selected prior to choosing the File ➪ New command. Select the Managed Object Class template from the New File assistant and click the Next button. Unlike most other new fi le templates, the Managed Object Class does not ask for a fi lename. The fi lename is generated from the names of the entities. You do need to choose a location for the fi les and the targets in which the Objective - C source fi les should be included. When you are done, click the Next button, and Xcode presents the pane shown in Figure 15 - 23. FIGURE 15-23 Check the entities for which you want to create custom implementation classes. By default, the entities that were selected in the model are already checked, but you are free to alter that here. You then need to pick any of the code generation options: Generate Accessors Generate Obj - C 2.0 Properties Generate Validation Methods The Generate Accessors option generates standard accessor methods for every property defi ned in the entity. These methods will be Key Value Coding, Key Value Observing, and Bindings compliant. The Generate Obj - C 2.0 Properties option augments the Generate Accessors option by producing modern Objective - C 2.0 @property and @synthesize directives, instead of emitting boilerplate Objective - C code. This option does nothing if the Generate Accessors option isn ’ t also selected. The Generate Validation Methods defi ne validation methods for every attribute defi ned. You can keep the ones you want and delete the ones you don ’ t need to override. ➤ ➤ ➤ Creating NSManagedObject Subclasses ❘ 335 c15.indd 335c15.indd 335 1/21/10 3:52:43 PM1/21/10 3:52:43 PM Download at getcoolebook.com 336 ❘ CHAPTER 15 DATA MODELING As of this writing, the Generate Obj - C 2.0 Properties object mysteriously defeats the Generate Validation Methods option. If you want Xcode to produce stub methods for validating your properties, leave the Generate Obj - C 2.0 Properties option off. You can easily replace the simplistic getters and setters with @property and @synthesize directives later. If the plan for your NSManagedObject subclass is to add special functionality, and not to customize the behavior of its properties, leave all of the code generation options unchecked. This generates empty subclasses of the selected entities. Core Data accesses the properties of NSManagedObject using a set of heuristics. If an object has an accessor defi ned for an attribute, that accessor is called to obtain or set the value. If not, the value is obtained using the default value method implemented in NSManagedObject. Only defi ne accessor and instance variables for special cases, and omit any code for properties you want handled normally by NSManagedObject. See the Subclassing Notes of the NSManagedObject documentation for more details. After your custom implementation class is defi ned, edit the data model so that the new class name is specifi ed in the Class fi eld of the entity ’ s details pane. Use the refactoring tool (Chapter 10) if you want to rename any of the generated class names fi rst. The inheritance of your custom classes does not have to parallel the inheritance of your entities. For example, say your data model defi nes the entity Vegetable, which inherits from Crop, which inherits from Plant. You then create custom NSManagedObject subclasses, MyCrop and MyVegetable, and assign those to the Crop and Vegetable entities, respectively. Here ’ s the surprising bit: MyVegetable isn ’ t required to be a subclass of MyCrop. It might seem strange, and I can ’ t imagine many practical uses, but it ’ s perfectly valid from Core Data ’ s perspective. Of course, you don ’ t have to use the Managed Object Class template. You are free to write your own subclass of NSManagedObject. It makes no difference to Xcode. Note that the accessor methods generated by Xcode include explicit calls to - willAccessValueforKey: , - didAccessValueForKey: , - willChangeValueForKey: , and so on. This is because NSManagedObjects disable the normal automatic messaging for Key Value Observing. You need to be mindful of this fact when implementing your own methods, which is another good reason to start with those generated by the template. EXPORTING CLASS METHODS The Managed Object Class template is a great time saver, but it ’ s a one - shot tool. You can ’ t modify your entity and use the template again. Doing so will either overwrite or replace the previous class fi les — a dialog box warns you that Xcode is about to replace the class fi les and asks what you want to do with the old ones. You either have to replicate your previous customizations or copy and paste from the old implementation. c15.indd 336c15.indd 336 1/21/10 3:52:43 PM1/21/10 3:52:43 PM Download at getcoolebook.com If you are simply adding new properties to an entity, there ’ s an easier way. Xcode will produce the same accessor methods that the template creates, but copy them to the clipboard instead. It will do this for any selected property, or properties, in the data browser. Select one or more properties and choose any of the following commands: Design ➪ Data Model ➪ Copy Method Declarations to Clipboard Design ➪ Data Model ➪ Copy Method Implementation to Clipboard Design ➪ Data Model ➪ Copy Obj - C 2.0 Method Declarations to Clipboard Design ➪ Data Model ➪ Copy Obj - C 2.0 Method Implementation to Clipboard Switch to the implementation or header fi le for the class, as appropriate, and paste in the new methods. IMPORTING DATA MODELS To import the data model in a compiled .mom document, open a data model document and choose the Design ➪ Data Model ➪ Import command. Select a compiled .mom document, and Xcode disassembles the fi le and adds the entities that it fi nds to the model. If you ’ re trying to import a .mom document contained in an application bundle, it ’ s a bit tricky because Xcode ’ s open fi le dialog won ’ t let you select fi les inside a package. To do that, fi rst open the contents of the application package in the Finder by Right/Control - clicking and choosing the Show Package Contents command. In Xcode, choose Design ➪ Data Model ➪ Import, and then drag the .mom fi le from the open Finder window into the open fi le dialog. Alternatively, press Shift+Command+G in the open fi le dialog and enter the path of the fi le or application bundle folder. Note that Shift+Command+G works in almost any Mac OS X open fi le dialog, and it supports POSIX shell - style pathname completion. SUMMARY Data modeling is a powerful tool. You can start incorporating the power of Core Data into your application in a matter of minutes, simply by creating an entity or two. Like class modeling, it is also a visualization tool, so you never lose sight of the “ picture ” of your data model throughout the course of your development. Instant interfaces make getting your application up and running quickly even easier. As your data schema evolves, versioning and migration tools will keep your data coming right along with you. ➤ ➤ ➤ ➤ Summary ❘ 337 c15.indd 337c15.indd 337 1/21/10 3:52:51 PM1/21/10 3:52:51 PM Download at getcoolebook.com c15.indd 338c15.indd 338 1/21/10 3:52:51 PM1/21/10 3:52:51 PM Download at getcoolebook.com . you. ➤ ➤ ➤ ➤ Summary ❘ 33 7 c15.indd 33 7c15.indd 33 7 1/21/10 3: 52:51 PM1/21/10 3: 52:51 PM Download at getcoolebook.com c15.indd 33 8c15.indd 33 8 1/21/10 3: 52:51 PM1/21/10 3: 52:51 PM Download at. ➤ ➤ ➤ Creating NSManagedObject Subclasses ❘ 33 5 c15.indd 33 5c15.indd 33 5 1/21/10 3: 52: 43 PM1/21/10 3: 52: 43 PM Download at getcoolebook.com 33 6 ❘ CHAPTER 15 DATA MODELING As of this writing,. implementation. c15.indd 33 6c15.indd 33 6 1/21/10 3: 52: 43 PM1/21/10 3: 52: 43 PM Download at getcoolebook.com If you are simply adding new properties to an entity, there ’ s an easier way. Xcode will produce