I tried to create a common encoder and decoder for my model classes. I tried to find a way to call the "encoding method" for all types of properties, or objects (NSString, NSNumber, NSArray, etc.), and primitive types. And I saw someone do the following. And I was wondering if this is the right thing to do.
Properties:
@property (assign,nonatomic) int integerP; @property (assign,nonatomic) float floatP; @property (assign,nonatomic) BOOL boolP;
Enconder and Decoder Code:
- (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"];
I was not sure if this was correct, or if another program or object could write primitive properties in the same memory space. If the above method is correct, what is the difference between the above and the following:
What I thought was right:
- (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeInt:integerP forKey:@"integerP"]; [encoder encodeFloat:floatP forKey:@"floatP"]; [encoder encodeBool:boolP forKey:@"boolP"];
I tested and both methods returned the correct values.
source share