Implement Archiving and Unarchiving (Save and Open)
Now that you have implemented and debugged all of To Do’s
major features, it’s time to finish up by adding support for saving
and opening documents to ToDoDocument.m
.
Implement dataRepresentationOfType:
As you learned previously, this method is responsible for archiving the document’s data and returning it in the form of an NSData instance. It’s very simple:
- (NSData *)dataRepresentationOfType:(NSString *)aType { [self saveDocItems]; return [NSArchiver archivedDataWithRootObject:activeDays]; }
This method saves the current day’s items to the
activeDays
dictionary and archives it.
Implement loadDataRepresentation:ofType:
This method checks to see if calendar
exists before
deciding how to proceed. If calendar
does exist, it
means that the nib file has already been loaded and the document
controller is being asked to display the data (this is what happens
when Revert is selected from the File menu). If
calendar
doesn’t yet exist (meaning the nib file
has not yet been loaded), the method saves a reference to the document
data in the dataFromFile
instance variable. When
windowControllerDidLoadNib
is called, that method
checks to see if any data is pending, and if it is, that data is
loaded into the document.
Add the instance variable
dataFromFile
toToDoDocument.h
. Statically type the variable as anNSData*
.Add the following method definition to
ToDoDocument.m
:- (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)aType ...
Get Learning Cocoa now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.