Wednesday, October 14, 2009

Instant Cocoa: Checkbook project 3


Saving NSData



If you make a document-based Cocoa project, you need to implement methods in MyDocument (or whatever you want to call it) to do the save and reloading. We talked the other day about what is needed to get an icon on the saved file and make it able to launch the app when double-clicked. In that post we used

writeToURL: ofType: error:
readFromURL: ofType: error:


This is a different approach to saving, using NSData. Here are the two functions to be implemented (note that they do not need to be re-declared). The model data is contained in a @synthesized variable called checkbookItemsArray. The try / catch code is straight out of Hillegass:


- (NSData *)dataOfType:(NSString *)typeName 
error:(NSError **)outError{
return [NSKeyedArchiver
archivedDataWithRootObject:checkbookItemsArray];
}

- (BOOL)readFromData:(NSData *)data
ofType:(NSString *)typeName
error:(NSError **)outError {
NSLog(@"about to read data of type %@", typeName);
@try {
dataIn = [NSKeyedUnarchiver
unarchiveObjectWithData:data];
}
@catch (NSException * e) {
if (outError) {
NSDictionary *d = [NSDictionary
dictionaryWithObject:@"The data is corrupted"
forKey:NSLocalizedFailureReasonErrorKey];
*outError = [NSError
errorWithDomain:NSOSStatusErrorDomain
code:unimpErr
userInfo:d];
}
return NO;
}
[self setCheckbookItemsArray:dataIn];
[myBalancer calculateBalance:checkbookItemsArray];
[myTV deselectAll:self];
return YES;
}