首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSKeyedUnarchiver -如何防止崩溃

NSKeyedUnarchiver -如何防止崩溃
EN

Stack Overflow用户
提问于 2011-09-26 23:53:57
回答 2查看 5K关注 0票数 8

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

代码语言:javascript
复制
    -(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,但不知道如何在我的代码中实现它。如果有任何例子我将不胜感激。提前感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-27 00:03:19

您可以使用@try{}@catch{}@finally包装解压调用。这在苹果文档中有描述:http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/ObjectiveC/Chapters/ocExceptionHandling.html

代码语言:javascript
复制
@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
}
票数 14
EN

Stack Overflow用户

发布于 2011-09-27 00:02:25

你有没有试过“try/catch”块?如下所示:

代码语言:javascript
复制
@try {
    self.libraryDat = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
@catch (NSException* exception) {
    NSLog(@"provide some logs here");
    // delete corrupted archive
    // initialize libraryDat from scratch
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7557800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档