2011-09-26 241 views
6

我想这是非常明显的,但我有一个关于加载数据的问题。如果有一个名为library.dat的文件,它存储有关应用程序中对象的所有类型的信息。它的设置都很好(根据initWithCoder和encodeWithCoder等方法),但我只是想知道如果library.dat被破坏会发生什么。我自己破坏了它,然后应用程序就会崩溃。有什么办法来防止崩溃?我可以在加载之前测试一个文件吗?这里是位,它可能会非常致命:NSKeyedUnarchiver - 如何防止崩溃

-(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,但不知道我应该怎么在我的代码实现这一点。我会很感激任何例子。提前致谢!

回答

13

你可以用@try {} @ catch {} @最后包装unarchive调用。这在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 
} 
+3

非常感谢您确认这是处理此问题的官方方式。 –

+1

NSInvalidUnarchiveOperationException是一个字符串,而不是一类Exception。所以我认为你必须抓住NSException,然后检查它的名字......? –

4

你试过'try/catch'块吗?类似这样的:

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

Thanks!我对此相当陌生,人们总是警告反对'try/catch'块。听起来在这种情况下非常合理,但。我想没有别的办法,只能使用块,对吧? –

+1

我认为没有其他简单的解决方案。不幸。 – igoris

+0

刚刚尝试过,但xCode告诉我“未知类型名称'NSInvalidUnarchiveOperationException'” - 我必须先定义它吗? –