Stanford CS193p: Developing Applications For iOS! Fall 2013-14
Stanford CS193p: Developing Applications For iOS! Fall 2013-14
Agenda
Core Data!
Storing your Model permanently in an object-oriented database.!
Homework!
Assignment 5 due Wednesday.! Final homework (Assignment 6) will be assigned Wednesday, due the next Wednesday.!
Wednesday!
Final Project Requirements! Core Data and UITableView! Core Data Demo!
Next Week!
Multitasking! Advanced Segueing! Map Kit?
Stanford CS193p! Fall 2013
Core Data
Database!
Sometimes you need to store large amounts of data or query it in a sophisticated manner.! But we still want it to be object-oriented objects!!
Get started with Core Data! by creating a Data Model! using New File
This section.
This template.
Name of the Data Model! (the visual map between classes and database Entities).
Attributes
Entities Relationships
and Fetched Properties! (but were not going to talk about them).
Then type its name here.! Well call this rst Entity Photo.! It will represent a database entry about a photo. Entities are analogous to classes. An Entity will appear in our code as an NSManagedObject (or subclass thereof).
Now we will add some Attributes.! Well start with the photos title.! Click here to add an Attribute.
Notice that we have an error.! Thats because our Attribute needs a type.
Set the type of the title Attribute.! All Attributes are objects.! Numeric ones are NSNumber.! Boolean is also NSNumber.! Binary Data is NSData.! Date is NSDate.! String is NSString.! Dont worry about Transformable.
Attributes are accessed on our NSManagedObjects via the methods valueForKey: and setValue:forKey:.! Or well also see how we can access Attributes as @propertys.
Stanford CS193p! Fall 2013
No more error!
You can see your Entities and Attributes in graphical form by clicking here.
This is the same thing we were just looking at, but in a graphical view.
These can be dragged around and positioned around the center of the graph.
There are a number of advanced features you can set on an Attribute but were just going to set its type.
Similar to outlets and actions, we can ctrl-drag to create Relationships between Entities.
From a Photos perspective,! this Relationship to a Photographer is who took the Photo
A Photographer can take many Photos, so well call this Relationship photos on the Photographer side.
See how Xcode notes the inverse relationship between photos and whoTook.
We also need to note that there can be many Photos per Photographer.
The double arrow here means! a to many Relationship! (but only in this direction).
The type of this Relationship in our Objective-C code will be an NSManagedObject (or a subclass thereof). The type of this Relationship in our Objective-C code will be NSSet (since it is a to many Relationship).
The Delete Rule says what happens to the pointed to Photos if we delete this Photographer. Nullify means set the whoTook pointer to nil.
Core Data
There are lots of other things you can do!
But we are going to focus on creating Entities, Attributes and Relationships.!
UIManagedDocument
UIManagedDocument
It inherits from UIDocument which provides a lot of mechanism for the management of storage.! If you use UIManagedDocument, youll be on the fast-track to iCloud support.! Think of a UIManagedDocument as simply a container for your Core Data database.!
Creating a UIManagedDocument
NSFileManager *fileManager = [NSFileManager defaultManager]; NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];!
NSString *documentName = @MyDocument; NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName]; UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];
This creates the UIManagedDocument instance, but does not open nor create the underlying le.
UIManagedDocument
How to open or create a UIManagedDocument!
First, check to see if the UIManagedDocuments underlying le exists on disk !
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path]];!
if it does not, create the document using ...! [document saveToURL:url / / could (should?) use document.fileURL property here
forSaveOperation:UIDocumentSaveForCreating competionHandler:^(BOOL success) {
UIManagedDocument
Example!
self.document = [[UIManagedDocument alloc] initWithFileURL:(URL *)url]; if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]]) { [document openWithCompletionHandler:^(BOOL success) { if (success) [self documentIsReady]; if (!success) NSLog(@couldnt open document at %@, url); }]; } else { [document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) { if (success) [self documentIsReady]; if (!success) NSLog(@couldnt create document at %@, url); }]; } / / cant do anything with the document yet (do it in documentIsReady).
UIManagedDocument
Once document is open/created, you can start using it!
But you might want to check the documentState when you do ...!
- (void)documentIsReady { if (self.document.documentState == UIDocumentStateNormal) {
Other documentStates!
UIDocumentStateClosed (you havent done the open or create yet)! UIDocumentStateSavingError (success will be NO in completion handler)! UIDocumentStateEditingDisabled (temporary situation, try again)! UIDocumentStateInConflict (e.g., because some other device changed it via iCloud)!
We dont have time to address these (you can ignore in homework), but know that they exist.
UIManagedDocument
Okay, document is ready to use, now what?!
Now you can get a managedObjectContext from it and use it to do Core Data stuff!!
- (void)documentIsReady { if (self.document.documentState == UIDocumentStateNormal) { ! NSManagedObjectContext *context = self.document.managedObjectContext; / / start doing Core Data stuff with context } } ! Okay, just a couple of more UIManagedDocument things before we start using that context
UIManagedDocument
Saving the document!
UIManagedDocuments AUTOSAVE themselves!!
However, if, for some reason you wanted to manually save (asynchronous!) !
[document saveToURL:document.fileURL forSaveOperation:UIDocumentSaveForOverwriting
/* block to execute when save is done */ }]; Note that this is almost identical to creation (just UIDocumentSaveForOverwriting is different).! This is a UIKit class and so this method must be called on the main queue.
competionHandler:^(BOOL success) {
UIManagedDocument
Multiple instances of UIManagedDocument on the same document!
This is perfectly legal, but understand that they will not share an NSManagedObjectContext.! Thus, changes in one will not automatically be reected in the other.! ! Youll have to refetch in other UIManagedDocuments after you make a change in one.! ! Conicting changes in two different UIManagedDocuments would have to be resolved by you!! Its exceedingly rare to have two writing instances of UIManagedDocument on the same le.! But a single writer and multiple readers? Less rare. But you need to know when to refetch.! ! You can watch (via radio station) other documents managedObjectContexts (then refetch).! Or you can use a single UIManagedDocument instance (per actually document) throughout.
NSNotification
How would you watch a documents managedObjectContext?!
- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [center addObserver:self selector:@selector(contextChanged:) name:NSManagedObjectContextDidSaveNotification object:document.managedObjectContext]; / / dont pass nil here! } - (void)viewWillDisappear:(BOOL)animated { [center removeObserver:self name:NSManagedObjectContextDidSaveNotification object:document.managedObjectContext]; [super viewWillDisappear:animated]; }
Stanford CS193p! Fall 2013
NSNotification
NSManagedObjectContextDidSaveNotification
- (void)contextChanged:(NSNotification *)notification { / / The notification.userInfo object is an NSDictionary with the following keys: NSInsertedObjectsKey / / an array of objects which were inserted NSUpdatedObjectsKey / / an array of objects whose attributes changed NSDeletedObjectsKey / / an array of objects which were deleted } !
Merging changes!
If you get notied that another NSManagedObjectContext has changed your database ! you can just refetch (if you havent changed anything in your NSMOC, for example).! or you can use the NSManagedObjectContext method:!
- (void)mergeChangesFromContextDidSaveNotification:(NSNotification *)notification;
Core Data
Okay, we have an NSManagedObjectContext, now what?!
We grabbed it from an open UIManagedDocuments managedObjectContext @property.! Now we use it to insert/delete objects in the database and query for objects in the database.
Core Data
Inserting objects into the database!
NSManagedObjectContext *context = aDocument.managedObjectContext; NSManagedObject *photo = [NSEntityDescription insertNewObjectForEntityForName:@Photo inManagedObjectContext:context];
! Note that this NSEntityDescription class method returns an NSManagedObject instance. All objects in the database are represented by NSManagedObjects or subclasses thereof.! ! An instance of NSManagedObject is a manifestation of an Entity in our Core Data Model*.! Attributes of a newly-inserted object will start out nil (unless you specify a default in Xcode).! ! * i.e., the Data Model that we just graphically built in Xcode!!
Core Data
How to access Attributes in an NSManagedObject instance!
You can access them using the following two NSKeyValueCoding protocol methods ...! - (id)valueForKey:(NSString *)key; ! - (void)setValue:(id)value forKey:(NSString *)key; ! You can also use valueForKeyPath:/setValue:forKeyPath: and it will follow your Relationships!!
Core Data
Changes (writes) only happen in memory, until you save !
Remember, UIManagedDocument autosaves.! When the document is saved, the context is saved and your changes get written to the database.! UIManagedDocumentDidSaveNotification will be broadcast at that point.! ! Be careful during development where you press Stop in Xcode (sometimes autosave is pending).
Core Data
But calling valueForKey:/setValue:forKey: is pretty ugly!
Theres no type-checking. And you have a lot of literal strings in your code (e.g. @thumbnailURL)!
What we really want is to set/get using @propertys!! No problem ... we just create a subclass of NSManagedObject!
The subclass will have @propertys for each attribute in the database. We name our subclass the same name as the Entity it matches (not strictly required, but do it). ! And, as you might imagine, we can get Xcode to generate both the header le @property entries, and the corresponding implementation code (which is not @synthesize, so watch out!).
Select both Entities.! Were going to have Xcode generate NSManagedObject subclasses for them for us.
Which Data Models to! generate subclasses for! (we only have one Data Model).
Which Entities to! generate subclasses for! (usually we choose all of them).
Pick which group you want your new classes to be stored! (default is often one directory level higher, so watch out).
This will make your @propertys be scalars! (e.g. int instead of NSNumber *) where possible.! Be careful if one of your Attributes is an NSDate, youll end up with an NSTimeInterval @property.
Here are the two subclasses of! NSManagedObject that were generated:! Photo.[mh] and Photographer.[mh]
Depending on the order Xcode generated Photo and Photographer, it might not have gotten whoTook s type (Photographer *) right (it might say NSManagedObject *).! If that happens, just generate again.
convenient methods for! adding/removing photos that this Photographer has taken.
What the heck is @dynamic?!! ! It says I do not implement the setter or getter for this property, but send me the message anyway and Ill use the Objective-C runtime to gure out what to do.! ! There is a mechanism in the Objective-C runtime to trap a message sent to you that you dont implement.! ! NSManagedObject does this and calls! valueForKey: or setValue:forKey:. Pretty cool.
Core Data
So how do I access my Entities Attributes with dot notation?!
/ / lets create an instance of the Photo Entity in the database !
NSManagedObjectContext *context = document.managedObjectContext; ! Photo *photo = [NSEntityDescription insertNewObjectForEntityForName:@Photo ! inManagedObjectContext:context];
/ / then set the attributes in our Photo using, say, an NSDictionary we got from Flickr ! e.g. photo.title = [flickrData objectForKey:FLICKR_PHOTO_TITLE];! / / the information will automatically be saved (i.e. autosaved) into our document by Core Data / / now heres some other things we could do too ! NSString *myThumbnail = photo.thumbnailURL; ! photo.lastViewedDate = [NSDate date]; ! photo.whoTook = ...; / / a Photographer object we created or got by querying! photo.whoTook.name = @CS193p Instructor; / / yes, multiple dots will follow relationships!
Stanford CS193p! Fall 2013
Core Data
What if I want to add code to my NSManagedObject subclass?!
For example, we might want to add a method or two (to the @propertys added by Xcode).! ! ! would be especially nice to add class methods to create and set up an object in the database! It ! (e.g. set all the properties of a Photo or Photographer using an NSDictionary from Flickr).! Or maybe to derive new @propertys based on ones in the database! (e.g. a UIImage based on a URL in the database). But that could be a problem if we edited Photo.m or Photographer.m ... Because you might want to modify your schema and re-generate those .h and .m les from Xcode! To get around this, we need to use an Objective-C feature called categories.! So lets take a moment to learn about that ...
Categories
Categories are an Objective-C syntax for adding to a class ...!
Without subclassing it. Without even having to have access to the code of the class (e.g. you dont need its .m).!
Examples!
NSAttributedString s drawAtPoint: method.
- Added by UIKit (since its a UI method) even though NSAttributedString is in Foundation. NSIndexPath s row and section properties (used in UITableView-related code). - Added by UIKit too, even though NSIndexPath is also in Foundation.!
Syntax!
@interface Photo (AddOn) - (UIImage *)image; @property (readonly) BOOL isOld; @end Categories have their own .h and .m les (usually ClassName+PurposeOfExtension.[mh]).!
Categories
Implementation!
@implementation Photo (AddOn) - (UIImage *)image / / image is not an attribute in the database, but photoURL is { NSURL *imageURL = [NSURL URLWithString:self.photoURL]; NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; return [UIImage imageWithData:imageData]; } - (BOOL)isOld / / whether this Photo was uploaded more than a day ago { return [self.uploadDate timeIntervalSinceNow] > -24*60*60; } @end Other examples ... sometimes we add @propertys to an NSManagedObject subclass via categories! to make accessing BOOL attributes (which are NSNumbers) more cleanly. Or we add @propertys to convert NSDatas to whatever the bits represent.
Any class can have a category added to it, but dont overuse/abuse this mechanism.
Stanford CS193p! Fall 2013
Categories
Most common category on an NSManagedObject subclass?!
Creation !
@implementation Photo (Create) + (Photo *)photoWithFlickrData:(NSDictionary *)flickrData inManagedObjectContext:(NSManagedObjectContext *)context {
/ see if a Photo for that Flickr data is already in the database Photo *photo = ...; / if (!photo) { photo = [NSEntityDescription insertNewObjectForEntityForName:@Photo inManagedObjectContext:context]; / / initialize the photo from the Flickr data / / perhaps even create other database objects (like the Photographer)
} return photo; } @end
Stanford CS193p! Fall 2013
Choose New File then pick Objective-C category from the Cocoa Touch section.
Enter the name of the category, as well as! the name of the class the categorys methods will be added to.
Xcode will create both the .h and the .m for the category.! Remember, you cannot use instance variables in this .m!
Well see an example of adding a method to the Photo class using this category in the demo next lecture.
Deletion
Deletion!
Deleting objects from the database is easy (sometimes too easy!)! [aDocument.managedObjectContext deleteObject:photo]; ! Make sure that the rest of your objects in the database are in a sensible state after this.! Relationships will be updated for you (if you set Delete Rule for relationship attributes properly).! And dont keep any strong pointers to photo after you delete it!!
prepareForDeletion
/ / we dont need to set our whoTook to nil or anything here (that will happen automatically)! / / but if Photographer had, for example, a number of photos taken attribute,! / / we might adjust it down by one here (e.g. self.whoTook.photoCount--).
} @end
Stanford CS193p! Fall 2013
Querying
So far you can ...!
Create objects in the database with insertNewObjectForEntityForName:inManagedObjectContext:. Get/set properties with valueForKey:/setValue:forKey: or @propertys in a custom subclass.! Delete objects using the NSManagedObjectContext deleteObject: method.!
Querying
Creating an NSFetchRequest!
Well consider each of these lines of code one by one ...
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@Photo]; request.fetchBatchSize = 20; request.fetchLimit = 100; request.sortDescriptors = @[sortDescriptor]; request.predicate = ...;
Querying
NSSortDescriptor!
When we execute a fetch request, its going to return an NSArray of NSManagedObjects.! NSArrays are ordered, so we should specify the order when we fetch. We do that by giving the fetch request a list of sort descriptors that describe what to sort by.
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@title ascending:YES selector:@selector(localizedStandardCompare:)];
The selector: argument is just a method (conceptually) sent to each object to compare it to others. Some of these methods might be smart (i.e. they can happen on the database side).! localizedStandardCompare: is for ordering strings like the Finder on the Mac does (very common). We give an array of these NSSortDescriptors to the NSFetchRequest because sometimes! we want to sort rst by one key (e.g. last name), then, within that sort, by another (e.g. rst name).! Examples: @[sortDescriptor] or @[lastNameSortDescriptor, firstNameSortDescriptor]
Stanford CS193p! Fall 2013
Querying
NSPredicate
This is the guts of how we specify exactly which objects we want from the database.!
Predicate formats!
Creating one looks a lot like creating an NSString, but the contents have semantic meaning.
NSString *serverName = @flickr-5; NSPredicate *predicate = [NSPredicate predicateWithFormat:@thumbnailURL contains %@, serverName];
Examples!
@uniqueId = %@, [flickrInfo objectForKey:@id] / / unique a photo in the database @name contains[c] %@, (NSString *) / / matches name case insensitively! @viewed > %@, (NSDate *) / / viewed is a Date attribute in the data mapping! @whoTook.name = %@, (NSString *) / / Photo search (by photographers name)! @any photos.title contains %@, (NSString *) / / Photographer search (not a Photo search)! Many more options. Look at the class documentation for NSPredicate.
Stanford CS193p! Fall 2013
Querying
NSCompoundPredicate
You can use AND and OR inside a predicate string, e.g. @(name = %@) OR (title = %@)! Or you can combine NSPredicate objects with special NSCompoundPredicates.
NSArray *array = @[predicate1, predicate2]; NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:array]; This predicate is predicate1 AND predicate2. Or available too, of course.
Advanced Querying
Key Value Coding!
Can actually do predicates like @photos.@count > 5 (Photographers with more than 5 photos).! @count is a function (there are others) executed in the database itself.!
https:/ /developer.apple.com/library/ios/documentation/cocoa/conceptual/KeyValueCoding/Articles/CollectionOperators.html.!
By the way, all this stuff (and more) works on dictionaries, arrays and sets too ! e.g. [propertyListResults valueForKeyPath:@[email protected]] on Flickr results! returns the average latitude of all of the photos in the results (yes, really)! e.g. @photos.photo.title.length" would return an array of the lengths of the titles of the photos!
NSExpression!
Advanced topic. Can do sophisticated data gathering from the database. No time to cover it now, unfortunately.! ! If interested, for both NSExpression and Key Value Coding queries, investigate ! NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@]; ! [request setResultType:NSDictionaryResultType]; / / fetch returns array of dicts instead of NSMOs! [request setPropertiesToFetch:@[@name, expression, etc.]];
Stanford CS193p! Fall 2013
Querying
Putting it all together!
Lets say we want to query for all Photographers ...!
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@Photographer];
! !
Querying
Executing the fetch!
NSManagedObjectContext *context = aDocument.managedObjectContext; ! NSError *error; ! NSArray *photographers = [context executeFetchRequest:request error:&error]; !
! Returns nil if there is an error (check the NSError for details).! Returns an empty array (not nil) if there are no matches in the database.! Returns an NSArray of NSManagedObjects (or subclasses thereof) if there were any matches.! You can pass NULL for error: if you dont care why it fails.! ! Thats it. Very simple really.
Query Results
Faulting!
The above fetch does not necessarily fetch any actual data.! It could be an array of as yet unfaulted objects, waiting for you to access their attributes.! Core Data is very smart about faulting the data in as it is actually accessed.! For example, if you did something like this ...!
for (Photographer *photographer in photographers) { NSLog(@fetched photographer %@, photographer); }
You may or may not see the names of the photographers in the output! (you might just see unfaulted object, depending on whether it prefetched them)! But if you did this ...!
for (Photographer *photographer in photographers) { NSLog(@fetched photographer named %@, photographer.name); }
... then you would denitely fault all the Photographers in from the database.! Thats because in the second case, you actually access the NSManagedObjects data.
Stanford CS193p! Fall 2013
Luckily, Core Data access is usually very fast, so multithreading is only rarely needed.! Usually we create NSManagedObjectContext using a queue-based concurrency model.! This means that you can only touch a context and its NSMOs in the queue it was created on.!
/ / do stuff with context in its safe queue (the queue it was created on)! }]; ! Note that the Q might well be the main Q, so youre not necessarily getting multithreaded.!
Core Data
There is so much more (that we dont have time to talk about)!!
Optimistic locking (deleteConflictsForObject:) Rolling back unsaved changes Undo/Redo Staleness (how long after a fetch until a refetch of an object is required?)
Coming Up
Homework!
Assignment 5 due Wednesday.! Final homework (Assignment 6) will be assigned Wednesday, due the next Wednesday.!
Wednesday!
Final Project Requirements! Core Data and UITableView! Core Data Demo!
Next Week!
Multitasking! Advanced Segueing! Map Kit?