Loading from a File

Loading means that there is already a file on the computer’s disk that we want to read and use in an application. Writing the code to load a file is usually considerably easier than writing the code to save it, because the hard work of figuring out which instance variables to save and getting them on the disk has (presumably) already been done.

A user can load a file into the MathPaper application by doing any of the following:

  • Choosing MathPaper’s File Open menu command and specifying a file in the Open panel

  • Choosing a file from MathPaper’s File Open Recent submenu

  • Double-clicking a MathPaper document file icon in the Finder

  • Dragging a MathPaper document on top of the MathPaper.app application icon and dropping it

The NSDocument framework handles all of these file-opening techniques for us automatically! All we need to do is to implement a single method called loadDataRepresentation:ofType: .

  1. Insert the following loadDataRepresentation:ofType method into the implementation of the MathController class in the file MathController.m:

                         - (BOOL)loadDataRepresentation:(NSData *)newHistory
                                                 ofType:(NSString *)aType
                         {
                             if ([aType isEqualToString:@"MathPaper"]) {
                                 MathDocument *temp;
                                 temp = [NSUnarchiver unarchiveObjectWithData:newHistory];
                                 if (temp) {
                                     [self setFrame:[temp frame] ];
                                     [self setHistory:[temp history] ];
                                     return YES;
                                 }
                             }
                             return NO;
                         }

When any of the actions described at the beginning of this section take place, the NSDocument architecture will open the ...

Get Building Cocoa Applications: A Step by Step Guide 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.