【问题标题】:Decode and then encode unknown class with NSKeyedArchiver?使用 NSKeyedArchiver 解码然后编码未知类?
【发布时间】:2013-08-25 16:28:24
【问题描述】:

我有一个来自 OS X 应用程序的项目文件,它是一个使用 NSKeyedArchiver 生成的 plist。我需要以编程方式更改其中的一个字符串。

基本上,它包含带有 Foundation 类的 NSDictionary 对象。但是有一个自定义类(GradientColor)。我自己定义了它,并尝试在 initWithCoder: 和 encodeWithCoder: 中什么都不做,但目标应用程序在尝试读取新生成的项目文件时崩溃。所以它在初始化时无法正确处理 nil 值。

在使用 initWithCoder:(NSCoder *)aDecoder 初始化类时,我能否知道哪些键对应于我的类,以便将它们原封不动地编码回来?

【问题讨论】:

  • 我相信您必须拥有自定义类的实现才能以相同的方式读取/写入数据..

标签: objective-c nskeyedarchiver nskeyedunarchiver


【解决方案1】:

我已经恢复了该类 (GradientColor) 的实现。实际上,它存储的数据量非常小:

@interface GradientColor : NSView <NSCoding> {
    float location;
    NSColor *color;
}
@end

@implementation GradientColor
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeFloat:location forKey:@"location"];
    [aCoder encodeObject:color forKey:@"color"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        location = [aDecoder decodeFloatForKey:@"location"];
        color = [aDecoder decodeObjectForKey:@"color"];
    }
    return self;
}
@end

我的版本什么都不做,而是像原始实现一样正确地序列化和反序列化。我已经在 plist 本身中查看了所需的键及其类型。现在我的 CLI 实用程序会生成有效的项目文件。

在这里我找到了一篇关于 NSKeyedArchive 内部结构的好帖子,对我帮助很大:http://digitalinvestigation.wordpress.com/2012/04/04/geek-post-nskeyedarchiver-files-what-are-they-and-how-can-i-use-them/

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多