【问题标题】:NSKeyedUnarchiver - how to prevent a crashNSKeyedUnarchiver - 如何防止崩溃
【发布时间】:2011-11-25 08:19:48
【问题描述】:

我想这很明显,但我有一个关于加载数据的问题。如果有一个名为 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 但不知道应该如何在我的代码中实现它。我会很感激任何例子。提前致谢!

【问题讨论】:

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


    【解决方案1】:

    您是否尝试过“try/catch”块?像这样的:

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

    【讨论】:

    • 谢谢!我对此很陌生,人们总是警告不要“尝试/捕获”块。不过,在这种情况下听起来很合理。我想除了使用积木之外别无他法,对吧?
    • 我认为没有其他简单的解决方案。不幸的是。
    • 刚试过这个,但 xCode 告诉我“未知类型名称 'NSInvalidUnarchiveOperationException'”——我必须事先定义吗?
    • 或者应该是@catch(NSException *exception)?
    • NSInvalidUnarchiveOperationExceptionnot 例外,它是一个字符串常量。应该是@catch (NSException* exception)
    【解决方案2】:

    您可以使用@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
    }
    

    【讨论】:

    • 非常感谢您确认这是处理此问题的官方方式。
    • NSInvalidUnarchiveOperationException 是一个字符串,而不是一个异常类。所以我认为你必须捕获 NSException,然后检查它的名称......?
    猜你喜欢
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多