objective-c - 在特定条件下 unarchiveObjectWithFile 崩溃

标签 objective-c ios cocoa exception plist

我有以下代码来读取存档数组:

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];

从设备中取出 plist 后,它看起来很奇怪(而且很空):

<?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];

关于objective-c - 在特定条件下 unarchiveObjectWithFile 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8649333/

相关文章:

ios - NSManagedObject ChangedValues 忽略字符串值

ios - 如何更改 CCTexture2D 颜色

iphone - 在 iTunes Connect 中,为什么分发证书已经存在?

ios - 如何从 NSString 中搜索并删除转义字符?

iphone - localizedCaseInsensitiveCompare : and caseInsensitiveCompare:? 有什么区别

iphone - 从核心数据获取请求中排除反向关系

iOS 动画 1+2 = 3. 3-2 != 1

ios - 按姓氏分组的 Core Data 家族成员

macos - 系统正在将不需要的项目添加到我的应用程序中的自定义上下文菜单中

objective-c - objective-c : Recognize if user is opening app for first time