NSKeyedUnarchiver - 如何防止崩溃

时间:2011-09-26 15:53:57

标签: iphone objective-c ios cocoa-touch nskeyedarchiver

我想这很明显,但我对加载数据有疑问。如果有一个名为library.dat的文件,它存储有关应用程序中对象的所有类型的信息。它设置得很好(就initWithCoder和encodeWithCoder方法等而言),但我只是想知道如果library.dat被破坏会发生什么。我自己损坏了一点,然后应用程序崩溃了。有没有办法防止崩溃?我可以在加载前测试文件吗?这是可能非常致命的一点:

    -(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];



}

我看了一下* NSInvalidUnarchiveOperationException,但不知道我应该如何在我的代码中实现它。我会感激任何例子。提前谢谢!

2 个答案:

答案 0 :(得分:14)

您最终可以使用@try {} @ catch {}包装unarchive调用。 Apple文档在此处对此进行了描述: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
}

答案 1 :(得分:4)

你试过'try / catch'块吗?像这样:

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