NSKeyedUnarchiver - 如何防止崩溃
我想这是非常明显的,但我有一个关于加载数据的问题。如果有一个名为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 但不知道应该如何在代码中实现它。如果有任何例子,我将不胜感激。提前致谢!
I guess this is very obvious, but I have a question about loading data. If have a file called library.dat which stores all kind of information about objects in the app. It's set up all nicely (in terms of the initWithCoder and encodeWithCoder methods etc.), but I was just wondering what happens if the library.dat ever gets corrupted. I corrupted it a bit myself and the app will then crash. Is there any way to prevent a crash? Can I test a file before loading it? Here is the bit which can potentially be very fatal:
-(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];
}
I had a look at *NSInvalidUnarchiveOperationException but have no idea how I should implement this in my code. I'd be grateful for any examples. Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 @try{}@catch{}@finally 包装取消归档调用。 Apple 文档对此进行了描述: http://developer.apple .com/library/mac/#documentation/cocoa/conceptual/ObjectiveC/Chapters/ocExceptionHandling.html
You can wrap the unarchive call with @try{}@catch{}@finally. This is described in Apple docs here: http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/ObjectiveC/Chapters/ocExceptionHandling.html
您尝试过“try/catch”块吗?像这样的东西:
Have you tried 'try/catch' blocks? Something like this: