ITP 342 Advanced Mobile App Dev Core Data
Persistent Data NSUser Defaults Typically used to save app preferences Property List (plist) in Documents Directory Data is in a dictionary or an array Coders and Keyed Archives NSCoder and NSKeyedArchiver support saving an arbitrary object graph into a binary file Direct SQLite Requires writing SQL queries to retrieve and save data Core Data Provides the flexibility of working with SQLite directly while insulating the app from the mechanics of working with the database 2
Core Data Core Data is a schema-driven object graph management and persistence framework Fundamentally, Core Data helps you to save model objects (in the sense of the modelview-controller design pattern) to a file and get them back again Core Data is available on ios 3.0 and later 3
Some Features of Core Data Modeling data objects with a visual model editor Automatic and manual migration tools to handle when object schema changes Establishing relationships between objects (one-toone, one-to-many, many-to-many) Storing data in separate files and different file formats Validation of object attributes Querying and sorting data Lazy loading data Interacting closely with ios table views Managing related object changes with commit and undo capabilities 4
Why use Core Data? With Core Data, the amount of code you write to support the model layer of your application is typically 50% to 70% smaller as measured by lines of code. It provides excellent security and error-handling. It offers best memory scalability of any competing solution. You can use templates in the Instruments application to measure Core Data s performance and to debug various problems. 5
What Core Data is Not Core Data is not a relational database or a relational database management system (RDBMS). Core Data provides an infrastructure for change management and for saving objects to and retrieving them from storage. It can use SQLite as one of its persistent store types. Core Data is not a silver bullet. Core Data does not remove the need to write code. Core Data does not rely on Cocoa bindings. Core Data integrates well with Cocoa bindings and leverages the same technologies and used together they can significantly reduce the amount of code you have to write but it is possible to use Core Data without bindings. 6
Basic Architecture Using the Core Data framework, most of this functionality is provided for you automatically, primarily through an object known as a managed object context (or just context ). The managed object context serves as your gateway to an underlying collection of framework objects collectively known as the persistence stack that mediate between the objects in your application and external data stores. 7
Example: Document management using Core Data Basic Architecture 8
Managed Objects and Contexts You can think of a managed object context as an intelligent scratch pad. When you fetch objects from a persistent store, you bring temporary copies onto the scratch pad where they form an object graph (or a collection of object graphs). You can then modify those objects however you like. Unless you actually save those changes, however, the persistent store remains unaltered. 9
Managed Objects and Contexts Model objects that tie into in the Core Data framework are known as managed objects. All managed objects must be registered with a managed object context. You add objects to the graph and remove objects from the graph using the context. The context tracks the changes you make, both to individual objects' attributes and to the relationships between objects. By tracking changes, the context is able to provide undo and redo support for you. It also ensures that if you change relationships between objects, the integrity of the object graph is maintained. 10
Fetch Requests To retrieve data using a managed object context, you create a fetch request. A fetch request is an object that specifies what data you want, for example, all Employees, or all Employees in the Marketing department ordered by salary, highest to lowest. A fetch request has three parts. Minimally it must specify the name of an entity (by implication, you can only fetch one type of entity at a time). It may contain a predicate object that specifies conditions that objects must match. It may contain an array of sort descriptor objects that specifies the order in which the objects should appear. 11
Fetch Request An example fetch request 12
Core Data Core Data lets us design our data models visually, without writing code, and stores that data model in the.xcdatamodeld file Xcode data model document Create entities in the data model editor Entity refers to the description of an object In code, create managed objects from those entities Managed object refers to actual concrete instances of that entity created at runtime 13
Entities An entity is made up of 3 types of properties 1. Attributes hold data An attribute serves the same function in a Core Data entity as an instance variable does in an Objective-C class 2. Relationships relationship between entities Relationships can be to-one and to-many 3. Fetched properties an alternative to a relationship Fetched properties allow you to create a query that is evaluated at fetch time to see which objects belong to the relationship 14
Key-Value Coding Instead of using accessors and mutators, you will use key-value coding to set properties or retrieve their existing values Similar to key-value coding in NSDictionary When working with a managed object, the key you will use to set or retrieve a property's value is the name of the attribute you which to set NSString *name = [mymanagedobject valueforkey:@"name"];! [mymanagedobject setvalue:@"tommy Trojan" forkey:@"name"];! 15
Backing Store These managed objects live in something called a persistent store or a backing store By default, the app implements it as an SQLite database stored in the app's Documents directory No SQL because Core Data does all the work Backing stores can also be implemented as binary flat files or event stored in an XML format It is possible to have multiple persistent stores If you're curious about how the backing store is created and configured, take a look at the AppDelegate.m file 16
Managed Object Context We don't work with the persistent store directly, instead we use a managed object context (often referred to as just a context) The context manages access to the persistent store and maintains information about which properties have changed since the last time an object was save Also registers all changes with the undo manager, meaning that you always have the ability to undo a single change or roll back all the way to the last time data was saved 17
Core Data Supported Data Types Data Types Integer 16 Integer 32 Integer 64 Decimal Double Float String Boolean Date Binary Data Transformable Objective-C Storage NSNumber NSNumber NSNumber NSNumber NSNumber NSNumber NSString NSNumber NSDate NSData Uses value transformer 18
Inheritance Core Data supports entity inheritance. Any entity can have one parent entitiy specified. The child entitiy will inherit all the characteristics of the parent entitiy, including attributes, validations, and indexes. 19
Core Data Project Project templates that allow you to select Core Data Master-Detail Application Utility Application Empty Application The Core Data framework will be included 20
Creating New Managed Objects Use insertnewobjectforentityforname: inmanagedobjectcontext: factory method in a class called NSEntityDescription! NSEntityDescription's job is to keep track of all the entities defined in the app's data model After the call, the object exist in the context but is not yet part of the persistent store until managed object context's save: method is called thename = [NSEntityDescription! insertnewobjectforentityforname:@"entityname"! inmanagedobjectcontext:context];! 21
Retrieving Managed Objects To retrieve, make use of a fetch request, which is Core Data's way of handling a predefined query Optionally, you can also specify criteria for a fetch request using the NSPredicate class A predicate is similar to the SQL WHERE clause and allows you to define the criteria used to determine the results of your fetch request You execute the fetch request using an instance method on NSMangedObjectContext: called executefetchrequest:error:! 22
Example NSFetchRequest *request = [[NSFetchRequest alloc] init];! NSEntityDescription *entitydescr = [NSEntityDescription! entityforname:@"entityname"! inmanagedobjectcontext:context];! [request setentity:entitydescr];!! // If predicate! NSPredicate *pred = [NSPredicate predicatewithformat:! @"(name = %@)", namestring];! [request setpredicate:pred];!! NSError *error;! NSArray *objects = [context executefetchrequest:request! error:&error];! if (objects == nil) {! // handle error! }! 23
New Project Create a new Empty Application Make sure to check the Use Core Data checkbox 24
Data Model New filed called CoreData.xcdatamodeld Click on the Add Entity icon along the bottom Rename new entity to represent the data you want to save For our example, change it to Person Click on the Add Attribute icon along the bottom Set the attribute and the type Add 3 attributes: color (String), name (String), number (Integer 16) Click on the file to open the data model editor Two views (lower right corner) Table mode Graph mode 25
Empty Application Create a ViewController File à New à File à Cocoa Touch (under ios) à Objective-C class Make it a subclass of UIViewController Create a storyboard File à New à File à User Interface (under ios) à Storyboard Name it something like MainStoryboard 26
Storyboard Use the Library add a View Controller On the Identity Inspector, set the class to your new class (USCViewController) Add 2 labels Add 4 textfields Create IBOutlets 27
Storyboard Under the Project Navigator, select the app target Under Summary, for the Main Storyboard, make sure to select the name of your story board (MainStoryboard) 28
Update App Delegate In the USCAppDelegate.m file in the application:didfinishlaunchingwit hoptions: method, remove the self.window code Just keep return YES! 29
Update View Controller In the USCViewController.m file in the viewdidload method Get the context and fetch a request For the objects, set the textfields Add an observer Update the applicationwillresignactive: method 30
Resources https://developer.apple.com/library/ios/ documentation/cocoa/conceptual/coredata/ cdprogrammingguide.html http://www.raywenderlich.com/934/core-dataon-ios-5-tutorial-getting-started http://www.appcoda.com/introduction-tocore-data/ 31