我想这是很明显的,但是我有一个关于加载数据的问题。如果有一个名为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,但不知道如何在我的代码中实现它。如果有任何例子我将不胜感激。提前感谢!
发布于 2011-09-27 00:03:19
您可以使用@try{}@catch{}@finally包装解压调用。这在苹果文档中有描述: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
}发布于 2011-09-27 00:02:25
你有没有试过“try/catch”块?如下所示:
@try {
self.libraryDat = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
@catch (NSException* exception) {
NSLog(@"provide some logs here");
// delete corrupted archive
// initialize libraryDat from scratch
}https://stackoverflow.com/questions/7557800
复制相似问题