我认为在我的情况下,DTO 模式应该包含对象读取/写入外部格式,如字典
// .h
@interface AccountDEM
@property (nonatomic, copy) NSString* userName;
@property (nonatomic, copy) NSString* userAuthToken;
@property (nonatomic) int userIdentifier;
// transfer between dictionary and object
@property (nonatomic, readonly) NSDictionary *serialized;
- (instancetype) initWithDictionary:(NSDictionary *)serialized;
@end
// .m
@interface AccountDEM
@property (nonatomic, strong) NSDictionary *dictionaryRepresentation;
@end
@implementaion
- (void)setObject:(id)object forKey:(id<NSCopying>)key {
if (key) {
if (obj) {
NSMutableDictionary *dictionary = [self.dictionaryRepresentation mutableCopy];
[dictionary removeObjectForKey:key];
self.dictionaryRepresentation = [dictionary copy];
}
else {
NSMutableDictionary *dictionary = [self.dictionaryRepresentation mutableCopy];
dictionary[key] = obj;
self.dictionaryRepresentation = [dictionary copy];
}
}
}
- (id)objectForKey:(id<NSCopying>)key {
if (!key) {
return nil;
}
return self.dictionaryRepresentation[key];
}
#pragma mark - Custom Getters/Setters
- (void)setUserName:(NSString *)userName {
[self setObject:userName forKey:@"UserName"];
}
- (NSString *)userName {
return
[self objectForKey:@"UserName"];
}
- (void)setUserAuthToken:(NSString *)userAuthToken {
[self setObject:userAuthToken forKey:@"UserAuthToken"];
}
- (NSString *)userAuthToken {
return
[self objectForKey:@"UserAuthToken"];
}
- (void)setUserIdentifier:(int)userIdentifier {
[self setObject:@(userIdentifier) forKey:@"UserIdentifier"];
}
- (int)userIdentifier {
return
[[self objectForKey:@"UserIdentifier"] intValue];
}
#pragma mark - Transfer
- (NSDictionary *)serialized {
return self.dictionaryRepresentation;
}
- (instancetype) initWithDictionary:(NSDictionary *)serialized {
self = [super init];
if (self) {
// any validation about serialized object
// and put it into dictionaryRepresentation
_dictionaryRepresentation = serialized;
}
return self;
}
@end