«Introduction to Core Data Programming Guide 11 Who Should Read This Document 11 Organization of This Document 11 See Also 13 Technology Overview 14 ...»
Core Data Programming
Introduction to Core Data Programming Guide 11
Who Should Read This Document 11
Organization of This Document 11
See Also 13
Technology Overview 14
Core Data Features 14
Why Should You Use Core Data? 15
What Core Data Is Not 15
Core Data Basics 17
Basic Core Data Architecture 17
Managed Objects and Contexts 20
Fetch Requests 20
Persistent Store Coordinator 21
Persistent Stores 22
Persistent Documents 23
Managed Objects and the Managed Object Model 24 Managed Object Models 26 Features of a Managed Object Model 26 Entities 26 Properties 27 Fetch Request Templates 29 User Info Dictionaries 29 Configurations 29 Using a Managed Object Model 31 Creating and Loading a Managed Object Model 31 Compiling a Data Model 31 Loading a Data Model 31 Problems May Arise if Your Project Contains More Than One Model 32 Changing the Schema Makes a Model Incompatible With Old Stores 33 Accessing and Using a Managed Object Model at Runtime 33 2012-09-19 | Copyright © 2004, 2012 Apple Inc. All Rights Reserved.
Creating Fetch Request Templates Programmatically 34 Accessing Fetch Request Templates 34 Localizing a Managed Object Model 35 Strings File 36 Setting a Localization Dictionary Programmatically 36 Managed Objects 38 Basics 38 Properties and Data Storage 39 Non-Standard Attributes 39 Dates and Times 39 Custom Managed Object Classes 39 Overriding Methods 40 Modeled Properties 40 Object Life-Cycle—Initialization and Deallocation 41 Validation 42 Faulting 42 Managed Object Accessor Methods 44 Overview 44 Custom implementation 44 Key-value coding access pattern 45 Dynamically-Generated Accessor Methods 45 Declaration 46 Implementation 47 Inheritance 47 Custom Attribute and To-One Relationship Accessor Methods 48 Custom To-Many Relationship Accessor Methods 51 Custom Primitive Accessor Methods 54 Creating and Deleting Managed Objects 56 Creating, Initializing, and Saving a Managed Object 56 Behind the Scenes of Creating a Managed Object 57 The Managed Object Context 57 The Entity Description 58 Creating a Managed Object 58 Assigning an Object to a Store 59 Deleting a Managed Object 60 Relationships 60 Deleted status and notifications 60 2012-09-19 | Copyright © 2004, 2012 Apple Inc. All Rights Reserved.
Fetching Managed Objects 61 Fetching Managed Objects 61 Retrieving Specific Objects 62 Fetching Specific Values 63 Fetching and Entity Inheritance 66 Using Managed Objects 67 Accessing and Modifying Properties 67 Attributes and to-one relationships 67 To-many relationships 68 Saving Changes 70 Managed Object IDs and URIs 70 Copying and Copy and Paste 71 Copying Attributes 71 Copying Relationships 72 Drag and Drop 73 Validation 73 Undo Management 74 Faults 75 Ensuring Data Is Up-to-Date 76 Refreshing an object 76 Merging changes with transient properties 77 Object Lifetime Management 79 The Role of the Managed Object Context 79 Breaking Relationship Strong Reference Cycles 80 Change and Undo Management 80 Relationships and Fetched Properties 82 Relationship Definitions in the Model 82 Relationship Fundamentals 82 Inverse Relationships 83 Relationship Delete Rules 84 Manipulating Relationships and Object Graph Integrity 85 Many-to-Many Relationships 86 Unidirectional Relationships 88 Cross-Store Relationships 89 Fetched Properties 89 Non-Standard Persistent Attributes 91 2012-09-19 | Copyright © 2004, 2012 Apple Inc. All Rights Reserved.
Introduction 91 Transformable Attributes 91 Custom Code 93 Basic Approach 93 Scalar Value Constraints 94 The Persistent Attribute 94 An Object Attribute 95 Scalar Values 98 A Non-Object Attribute 99 Type-Checking 101 Managed Object Validation 103 Core Data Validation 103 Property-Level Validation 104 Inter-Property validation 105 Combining Validation Errors 108 Faulting and Uniquing 110 Faulting Limits the Size of the Object Graph 110 Firing Faults 111 Turning Objects into Faults 111 Faults and KVO Notifications 112 Uniquing Ensures a Single Managed Object per Record per Context 112 Using Persistent Stores 115 Creating and Accessing a Store 115 Changing a Store’s Type and Location 116 Associate Metadata With a Store to Provide Additional Information and Support Spotlight Indexing 117 Getting the Metadata 118 Setting the Metadata 118 Core Data and Cocoa Bindings 120 Additions to Controllers 120 Automatically Prepares Content Flag 121 Entity Inheritance 121 Filter Predicate for a To-many Relationship 122 Change Management 124 Disjoint Edits 124 Conflict Detection and Optimistic Locking 125 2012-09-19 | Copyright © 2004, 2012 Apple Inc. All Rights Reserved.
Conflict Resolution 126 Snapshot Management 126 Communicating Changes Between Contexts 127 Persistent Store Features 130 Store Types and Behaviors 130 Store-specific behavior 131 Custom store types 131 Security 131 Fetch Predicates and Sort Descriptors 132 SQLite Store 132 File-systems supported by the SQLite store 132 File Size May Not Reduce After Deleting a Record 133 Configuring a SQLite Store’s Save Behavior 133 Concurrency with Core Data 136 Use Thread Confinement to Support Concurrency 136 Track Changes in Other Threads Using Notifications 137 Fetch in the Background for UI Responsiveness 138 Saving in a Background Thread is Error-prone 138 If You Don’t Use Thread Containment 139 Core Data Performance 140 Introduction 140 Fetching Managed Objects 141 Fetch Predicates 141 Fetch Limits 141 Faulting Behavior 142 Batch Faulting and Pre-fetching with the SQLite Store 142 Reducing Memory Overhead 145 Large Data Objects (BLOBs) 146 Analyzing Performance 147 Analyzing Fetch Behavior with SQLite 147 Instruments 147 Troubleshooting Core Data 149 Object Life-Cycle Problems 149 Merge errors 149 Assigning a managed object to a different store 149 Fault cannot be fulfilled 150 2012-09-19 | Copyright © 2004, 2012 Apple Inc. All Rights Reserved.
Managed object invalidated 151 Class is not key-value coding compliant 151 Entity class does not respond to invocations of custom methods 152 Custom accessor methods are not invoked, key dependencies are not obeyed 152 Problems with Fetching 152 SQLite store does not work with sorting 152 Problems with Saving 153 SQLite store takes a "long time" to save 153 Cannot save documents because entity is null 154 Exception generated in retainedDataForObjectID:withContext. 154 Debugging Fetching 155 Managed Object Models 156 My application generates the message "+entityForName: could not locate an NSManagedObjectModel" Bindings Integration 157 Custom relationship set mutator methods are not invoked by an array controller 157 Cannot access contents of an object controller after a nib is loaded 157 Cannot create new objects with array controller 158 A table view bound to an array controller doesn't display the contents of a relationship 158 A new object is not added to the relationship of the object currently selected in a table view 158 Table view or outline view contents not kept up-to-date when bound to an NSArrayController or NSTreeController object 159 Efficiently Importing Data 160 Cocoa Fundamentals 160 Reducing Peak Memory Footprint 161 Importing in batches 161 Dealing with strong reference cycles 162 Implementing Find-or-Create Efficiently 162 Core Data FAQ 165 Where does a Managed Object Context Come From? 165 How do I initialize a store with default data? 165 How do I use my existing SQLite database with Core Data? 166 I have a to-many relationship from Entity A to Entity B. How do I fetch the instances of Entity B related to a given instance of Entity A? 166 How do I fetch objects in the same order I created them? 167 How do I copy a managed object from one context to another? 167 I have a key whose value is dependent on values of attributes in a related entity—how do I ensure it is kept up to date as the attribute values are changes and as the relationship is manipulated? 167 2012-09-19 | Copyright © 2004, 2012 Apple Inc. All Rights Reserved.
OS X v10.5 and later for a to-one relationship 167 To-many relationships 168 In Xcode’s predicate builder, why don’t I see any properties for a fetched property predicate? 170 How efficient is Core Data? 170 Core Data looks similar to EOF.
What are the differences? 170 Features Supported Only by EOF 170 Features Supported Only by Core Data 170 Class Mapping 171 Change Management 171 Multi-Threading 171 OS X Desktop 171 How do I get the GUI to validate the data entered by the user? 171 When I remove objects from a detail table view managed by an array controller, why are they not removed from the object graph? 172 How do I get undo/redo for free in my non-document-architecture-based app? 172 Document Revision History 173 Glossary 176
Core Data Basics 17 Figure 1 Document management using the standard Cocoa document architecture 18 Figure 2 Document management using Core Data 19 Figure 3 An example fetch request 21 Figure 4 Advanced persistence stack 22 Figure 5 Managed object model with two entities 24 Figure 6 Entity description with two attributes and a relationship 24 Managed Object Models 26 Figure 1 Selecting a parent entity in Xcode 27 Figure 2 Xcode predicate builder 29 Using a Managed Object Model 31 Table 1 Keys and values in a localization dictionary for a managed object model 35 Listing 1 Creating a fetch request template programmatically 34 Listing 2 Using a fetch request template 35 Listing 3 Creating a managed object model in code 37 Managed Object Accessor Methods 44 Listing 1 Implementation of a custom managed object class illustrating attribute accessor methods 48 Listing 2 Implementation of a custom managed object class illustrating copying setter 50 Listing 3 Implementation of a custom managed object class illustrating a scalar attribute value 50 Listing 4 A managed object class illustrating implementation of custom accessors for a to-many relationship Fetching Managed Objects 61 Listing 1 Example of creating and executing a fetch request 61 Relationships and Fetched Properties 82 Figure 1 Transferring an employee to a new department 85 Figure 2 Example of a reflexive many-to-many relationship 86 Figure 3 A model illustrating a “friends” relationship using an intermediate entity 87 Managed Object Validation 103 2012-09-19 | Copyright © 2004, 2012 Apple Inc. All Rights Reserved.
Listing 1 Inter-property validation for a Person entity 106 Listing 2 A method for combining two errors into a single multiple errors error 108 Faulting and Uniquing 110 Figure 1 A department represented by a fault 110 Figure 2 Independent faults for a department object 113 Figure 3 Uniqued fault for two employees working in the same department 113 Change Management 124 Figure 1 Managed object contexts with mutually inconsistent data values 125
The Core Data framework provides generalized and automated solutions to common tasks associated with object life-cycle and object graph management, including persistence.
Who Should Read This Document You should read this document to gain an understanding of the Core Data framework. You must be familiar with the basics of Cocoa development, including the Objective-C language and memory management.
Important: Although this document provides a thorough treatment of the fundamentals of the Core Data framework, simply reading from start to finish is not a good strategy for learning how to use the technology effectively. Instead, you should typically augment your understanding by following the related tutorials provided in the Reference Library. For a description of the recommended learning path, see Core Data Starting Point.
Organization of This Document The following articles explain the problems the Core Data Framework addresses, the solutions it provides, its
basic functionality, and common tasks you might perform:
“Technology Overview” (page 14) describes what Core Data is and why you might choose to use it.
● “Core Data Basics” (page 17) describes the fundamental architecture of the technology.
● “Managed Object Models” (page 26) describes the features of a managed object model.
● “Using a Managed Object Model” (page 31) describes how you use a managed object model in your ● application.
“Managed Objects” (page 38) describes the features of a managed object, the NSManagedObject class, ● and how and why you might implement a custom class to represent an entity.
“Managed Object Accessor Methods” (page 44) describes how to write accessor methods for custom ● managed objects.