iphone - NSKeyedUnarchiver - 如何防止崩溃

标签 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 但不知道我应该如何在我的代码中实现它。我会很感激任何例子。提前致谢!

最佳答案

您可以使用@try{}@catch{}@finally 包装取消归档调用。这在 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
}

关于iphone - NSKeyedUnarchiver - 如何防止崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7557800/

相关文章:

iphone - 如何检查是否已调用此方法?

iphone - 使用启动图像作为 ViewController 背景图像

ios - 按停止按钮时 AVAudioPlayer 不恢复

ios - 如何在 uipageviewcontroller swift 中转换时隐藏导航栏

iphone - 如何让 UITextField 响应 UITextFieldDelegate?

iphone - Cocoa 对象数组转字符串

iphone - 如何在 iOS 中将 unsigned char 转换为 NSString

objective-c - 带有大图像的 Objective C iPad 动画 - 使用什么方法?

objective-c - NSMutableDictionary 和新项目插入 KVO

android - 为跨平台 OpenGL ES 2.0+ 引擎选择语言和设计 - iOS 和 Android