To add the ability to save and reopen a task list, you need to override two methods inherited from BNRDocument’s superclass, NSDocument:
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError { // This method is called when our document is being saved // You are expected to hand the caller an NSData object wrapping our data // so that it can be written to disk // If there is no array, write out an empty array if (!self.tasks) { self.tasks = [NSMutableArray array]; } // Pack the tasks array into an NSData object NSData *data = [NSPropertyListSerialization dataWithPropertyList:self.tasks format:NSPropertyListXMLFormat_v1_0 options:0 error:outError]; // Return the newly-packed NSData object return data; } - (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError { // This method is called when a document is being loaded // You are handed an NSData object and expected to pull our data out of it // Extract the tasks self.tasks = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainers format:NULL error:outError]; // return success or failure depending on success of the above call return (self.tasks != nil); }
Notice that you are implementing a method that takes in an NSError**. In this case, you are merely handing back the NSError generated by propertyListWithData:options:format:error:, but you could also create and hand back a new NSError as well, depending on the nature of the failure.
Build and run the application again. Add some tasks to the list. Save and close the list (using the familiar menu commands or keyboard shortcuts), and then reopen it. Congratulations! TahDoodle is complete.
So when should you use Interface Builder to create your user interface and when should you set up views programmatically? Under simple circumstances, either will work. iTahDoodle’s interface could have been built using Interface Builder; TahDoodle’s views could have been created programmatically.
In general, however, the more complex your user interface, the more sense it makes to use Interface Builder.
Now that you have seen more of Xcode, take a look at the tear-out card at the back of this book. This card contains keyboard shortcuts for navigating around Xcode. As you continue with Xcode, use this card to find shortcuts that will save you time and clicks.