我有一个 MyCustomClass
类的对象,有四个不同类型的属性:
@property (nonatomic, assign) double someDouble;
@property (nonatomic, assign) NSInteger someInteger;
@property (nonatomic, retain) NSColor* someColor;
@property (nonatomic, retain) NSData* someData;
我采用了 NSSecureCoding 并对我的课程进行了编码:
-(void)encodeWithCoder:(NSCoder *)encoder;
{
for (NSString* key in [self propertyKeys])
[encoder encodeObject:[self valueForKey:key] forKey:key];
}
-(NSArray *)propertyKeys
{
return [NSArray arrayWithObjects:@"someDouble", @"someInteger", @"someColor", @"someData", nil];
}
然后我解码:
-(id)initWithCoder:(NSCoder *)decoder
{
if (self = [self init])
{
for (NSString* key in [self propertyKeys])
{
if ([decoder containsValueForKey:key])
{
id object = [decoder decodeObjectOfClasses:[self allowedClasses] forKey:key];
[self setValue:object forKey:key];
}
}
}
return (self);
}
-(NSSet *)allowedClasses
{
return ([NSSet setWithObjects:[NSColor class], nil]);
}
所以:
为什么我只需要在允许的类中有 NSColor
?尽管我没有添加 NSData 或 NSNumber,但所有这些代码都有效,因为我认为 KVC 正在处理原始类型(NSInteger 和 double)到 NSNumber 的转换。