我试图为我的模型类创建一个通用的编码器和解码器。我试图找到一种方法来为所有类型的属性调用“编码方法”,无论是对象(NSString、NSNumber、NSArray 等)还是原始类型。我看到有人在做以下事情。我想知道这是否是正确的方法。
特性:
@property (assign,nonatomic) int integerP;
@property (assign,nonatomic) float floatP;
@property (assign,nonatomic) BOOL boolP;
编码器和解码器代码:
- (void)encodeWithCoder:(NSCoder *)encoder
{
id object2 = [self valueForKey:@"integerP"];
id object3 = [self valueForKey:@"floatP"];
id object4 = [self valueForKey:@"boolP"];
[encoder encodeObject:object2 forKey:@"integerP"];
[encoder encodeObject:object3 forKey:@"floatP"];
[encoder encodeObject:object4 forKey:@"boolP"];
//[self setValue:[NSNumber numberWithInt:90] forKey:@"heightR"];
//NSLog(@"%@",[self valueForKey:@"heightR"]);
}
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if( self != nil )
{
id object2 = [decoder decodeObjectForKey:@"integerP"];
[self setValue:object2 forKey:@"integerP"];
id object3 = [decoder decodeObjectForKey:@"floatP"];
[self setValue:object3 forKey:@"floatP"];
id object4 = [decoder decodeObjectForKey:@"boolP"];
[self setValue:object4 forKey:@"boolP"];
}
return self;
}
我不确定这是否是正确的方式,或者其他程序或对象是否可以写入原始属性的相同内存空间。如果上面的方法是正确的,那么上面和这个有什么区别:
我认为正确的方式:
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeInt:integerP forKey:@"integerP"];
[encoder encodeFloat:floatP forKey:@"floatP"];
[encoder encodeBool:boolP forKey:@"boolP"];
//[self setValue:[NSNumber numberWithInt:90] forKey:@"heightR"];
//NSLog(@"%@",[self valueForKey:@"heightR"]);
}
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if( self != nil )
{
integerP = [decoder decodeIntForKey:@"integerP"];
floatP = [decoder decodeFloatForKey:@"floatP"];
boolP = [decoder decodeBoolForKey:@"boolP"];
}
return self;
}
我进行了测试,两种方法都返回了正确的值。