Example code programming Objective-C with Cocoa in Xcode and Interface Builder (Leopard)
7: Archiving using NSKeyedArchiver variant of NSArchiver
Implement simple code archive using NSKeyedArchiver, NSKeyedUnarchiver, encodeWithCoder, initWithCoder which are a variant on using NSArchiver, NSUnarchiver .
Create a new project in XCode: File->New Project->Cocoa Application
Call it: 007-NSKeyedArchiver
Now create the class: MySaveMenuController of type NSObject.
and the class: MyProgData of type NSObject.
Code these as shown below and save.
Note: if you have already done the NSArchiver example then just duplicate the 008-NSArchiver folder
and rename the project using Rename Xcode Project
// MySaveMenuController.h
// 007-save
#import <Cocoa/Cocoa.h>
#import "MyProgData.h"
@interface MySaveMenuController : NSMenu {
MyProgData * myMyProgDataObj;
}
- (IBAction)doTheSave:(id)pId;
- (IBAction)doTheLoad:(id)pId;
@end
// MySaveMenuController.m
// 007-save
#import "MySaveMenuController.h"
@implementation MySaveMenuController
- (IBAction)doTheSave:(id)pId; {
BOOL tvarResult = [NSKeyedArchiver archiveRootObject:myMyProgDataObj toFile:@"../../../007_MySavedFile"];
if (tvarResult) {
int tvarInt = [myMyProgDataObj myNumber];
NSLog(@"doTheSave succeded: tvarInt = %3d",tvarInt);
} else {
NSLog(@"doTheSave failed");
} // end if
} // end doIt
- (IBAction)doTheLoad:(id)pId; {
myMyProgDataObj = [NSKeyedUnarchiver unarchiveObjectWithFile:@"../../../007_MySavedFile"];
if (myMyProgDataObj) {
int tvarInt = [myMyProgDataObj myNumber];
NSLog(@"doTheLoad succeded: tvarInt = %3d",tvarInt);
} else {
NSLog(@"doTheLoad failed");
myMyProgDataObj = [[MyProgData alloc]initWithCoder:nil];
} // end if
} // end doIt
@end
// MyProgData.h
// 007-save
#import <Cocoa/Cocoa.h>
@interface MyProgData : NSObject
Bring up Interface Builder by double clicking on MainMenu.nib.
Select the File menu. Inside the Class menu of the Identity panel of the inspector choose MySaveMenuController. You will see the doTheLoad and doTheSave in the actions section.
Interface Builder: NSMenu object, its class and actions
Drag a Menu Item from the IB Library and insert it just above the 'Save' item in the File Menu. Double click on it to select its text and change it from 'Item' to 'Load'.
Interface Builder: name the new menu item
Click on File to select it.
In the connections panel of the Inspector drag from the round circles of doTheLoad and doTheSave to the Load and Save manu items respectively.
Interface Builder link menu items to actions
Save Interface Builder
Return to XCode, build and run.
Do File->Load, File-Save and Quit then repeat.
Run
Console Log
Double click on the file '007_MySavedFile'
It will open in the Property List Editor.
You will see the saved number in there.
Result seen inside the Property List Editor
If you want to download the code
Click the Download Link to obtain 007-NSKeyedArchiver.zip file of this whole OS X 10.5 Leopard program.