[英]How to prevent crash on corrupt file with [NSKeyedUnarchiver unarchiveObjectWithFile]?
[英]Crash in unarchiveObjectWithFile under specific conditions
我有以下代碼來讀取存檔數組:
id temp = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
if(temp && [temp isKindOfClass:[NSArray class]])
{
self.posts = [temp mutableCopy];
}
以下代碼是保存數組
-(void)savePostList
{
NSURL *tempURL = [[[ZZAppDelegate sharedAppDelegate] applicationCacheDirectory] URLByAppendingPathComponent:@"postCache.plist"];
[NSKeyedArchiver archiveRootObject:self.posts
toFile:[tempURL path]];
}
通常情況下一切都很完美,但是在非常特殊(當前未確定)的情況下,應用程序在啟動時會因異常而崩潰:
-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x275900
崩潰實際上是在調用內部發生的:
id temp = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
從設備中拔出鉗子后,它看起來非常奇怪(而且非常空):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array/>
</plist>
如果我將整個事物包裝在@try / @catch子句中,那么“一切都很好”,如下所示:
@try {
id temp = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
if(temp && [temp isKindOfClass:[NSArray class]])
{
self.posts = [temp mutableCopy];
if(self.posts)
{
[self precacheImages];
}
}
}
@catch (NSException *exception) {
// exception thrown - delete file
NSLog(@"An exception occurred reading file - deleting");
NSError * err;
if(![[NSFileManager defaultManager] removeItemAtPath:path error:&err])
{
NSLog(@"Error deleting file: %@", err);
}
}
我的問題是:有沒有人知道是什么會導致這種情況(如.plist中的'空')然后對unarchiveObjectWithFile調用引起異常(根據堆棧跟蹤在系統內部)圖書館)。
你會想要更像這樣的東西來反序列化plist
NSArray * someArray = [NSPropertyListSerialization dataFromPropertyList: [NSData dataWithContentsOfFile:path] format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.