n.evermind
n.evermind

Reputation: 12004

NSKeyedUnarchiver - how to prevent a crash

I guess this is very obvious, but I have a question about loading data. If have a file called library.dat which stores all kind of information about objects in the app. It's set up all nicely (in terms of the initWithCoder and encodeWithCoder methods etc.), but I was just wondering what happens if the library.dat ever gets corrupted. I corrupted it a bit myself and the app will then crash. Is there any way to prevent a crash? Can I test a file before loading it? Here is the bit which can potentially be very fatal:

    -(void)loadLibraryDat {

    NSLog(@"loadLibraryDat...");
    NSString *filePath = [[self documentsDirectory] stringByAppendingPathComponent:@"library.dat"];

    // if the app crashes here, there is no way for the user to get the app running- except by deleting and re-installing it...
    self.libraryDat = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];



}

I had a look at *NSInvalidUnarchiveOperationException but have no idea how I should implement this in my code. I'd be grateful for any examples. Thanks in advance!

Upvotes: 8

Views: 5209

Answers (2)

igoris
igoris

Reputation: 1476

Have you tried 'try/catch' blocks? Something like this:

@try {
    self.libraryDat = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
@catch (NSException* exception) {
    NSLog(@"provide some logs here");
    // delete corrupted archive
    // initialize libraryDat from scratch
}

Upvotes: 4

jaminguy
jaminguy

Reputation: 25940

You can wrap the unarchive call with @try{}@catch{}@finally. This is described in Apple docs here: http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/ObjectiveC/Chapters/ocExceptionHandling.html

@try {
    self.libraryDat = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
} @catch ( NSInvalidUnarchiveOperationException *ex ) {
    //do whatever you need to in case of a crash
} @finally {
    //this will always get called even if there is an exception
}

Upvotes: 14

Related Questions