通过NSSecureCoding解码NSArray时的奇怪行为 [英] Strange behavoir when decoding an NSArray via NSSecureCoding

查看:412
本文介绍了通过NSSecureCoding解码NSArray时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了整个下午的时间撞到墙上试图弄清楚为什么这门课的解码失败了。该类有一个属性,它是Foo对象的NSArray。 Foo符合NSSecureCoding,我已经成功编码并解码了该类。我在initWithCoder中遇到错误:表示无法解码类Foo。通过一些实验,我发现我需要将[Foo类]添加到initWithCoder:为了使它工作。也许这会帮助那些遇到同样问题的人。我的问题是,为什么这是必要的?我没有发现在Apple的文档中这是必要的。

  #importFoo.h

@interface MyClass:NSObject< NSSecureCoding>
@property(nonatomic)NSArray * bunchOfFoos;
@end

@implementation MyClass

static NSString * kKeyFoo = @kKeyFoo;

+(BOOL)supportsSecureCoding
{
返回YES;
}

- (void)encodeWithCoder:(NSCoder *)编码器
{
[编码器编码对象:self.bunchOfFoos forKey:kKeyFoo];
}

- (id)initWithCoder:(NSCoder *)解码器
{
if(self = [super init])
{
[Foo类]; //没有这个,解码失败
_bunchOfFoos = [decoder decodeObjectOfClass:[NSArray class] forKey:kKeyFoo];
}
返回自我;
}

@end


解决方案

我想我可能已经弄明白了。没有行[Foo class],这个文件中没有类Foo的引用。因此,我相信编译器正在优化Foo类,然后无法解码数组中的Foo对象。在那里有[Foo class]可以防止这种情况。


i spent all afternoon banging my head against the wall trying to figure out why decoding of this class was failing. the class has a property that is an NSArray of Foo objects. Foo conforms to NSSecureCoding, and i have successfully encoded and decoded that class by itself. i was getting an error in initWithCoder: that said failed to decode class Foo. through some experimentation, i discovered that i needed to add [Foo class] to initWithCoder: in order for it to work. maybe this will help someone else who's having the same problem. my question is, why is this necessary? i found no suggestion that this is necessary in apple's documentation.

#import "Foo.h"

@interface MyClass : NSObject <NSSecureCoding>
@property (nonatomic) NSArray *bunchOfFoos;
@end

@implementation MyClass

static NSString *kKeyFoo = @"kKeyFoo";

+ (BOOL) supportsSecureCoding
{
    return YES;
}

- (void) encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:self.bunchOfFoos forKey:kKeyFoo];
}

- (id) initWithCoder:(NSCoder *)decoder
{
    if (self = [super init])
    {
        [Foo class]; // Without this, decoding fails
        _bunchOfFoos = [decoder decodeObjectOfClass:[NSArray class] forKey:kKeyFoo];
    }
    return self;
}

@end

解决方案

i think i may have figured this out. without the line [Foo class], there is no reference to the class Foo in this file. because of this, i believe the compiler is optimizing the Foo class out, and then the Foo objects within the array cannot be decoded. having [Foo class] in there prevents this.

这篇关于通过NSSecureCoding解码NSArray时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆