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!
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With