我试图为我的模型类创建一个通用的编码器和解码器.我试图找到一种方法来为所有类型的属性调用“编码方法”,无论是对象(NSString,NSNumber,NSArray等)还是原始类型.我看到有人在做以下事情.我想知道这是否是一种正确的方法.
属性:
@property (assign,nonatomic) int integerP; @property (assign,nonatomic) float floatP; @property (assign,nonatomic) BOOL boolP;
Enconder和解码器代码:
- (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; }
我测试了,两种方法都返回了正确的值.