n.e*_*ind 7 iphone cocoa-touch objective-c nskeyedarchiver ios
我想这很明显,但我有一个关于加载数据的问题.如果有一个名为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];
}
Run Code Online (Sandbox Code Playgroud)
我看了一下*NSInvalidUnarchiveOperationException,但不知道我应该如何在我的代码中实现它.我会感激任何例子.提前致谢!
jam*_*guy 14
您最终可以使用@try {} @ catch {} @包装unarchive调用.Apple docs在此处对此进行了描述: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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4789 次 |
最近记录: |