通过NSSecureCoding解码NSArray时的奇怪行为 [英] Strange behavoir when decoding an NSArray via NSSecureCoding
问题描述
#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屋!