我有以下代码来读取存档数组:
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调用以它的方式引起异常(根据堆栈跟踪在里面)系统库)。
答案 0 :(得分:0)
你会想要更像这样的东西来反序列化plist
NSArray * someArray = [NSPropertyListSerialization dataFromPropertyList: [NSData dataWithContentsOfFile:path] format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];