PropertyMapping
在进行数据的映射之前,我们需要定义Object(本文中所有Object都表示一个复杂的Object对象)中每一个property的映射关系PropertyMapping,其中ObjectMapping是标示当前property是否是一个Object,如果是nil,则表示当前property就是简单的映射。如果不是nil,则需要将property进行展开,把当前的property当成另外一个Object进行映射。
#import <Foundation/Foundation.h>
@class ObjectMapping;
@interface PropertyMapping : NSObject
@property (nonatomic, weak) ObjectMapping *objectMapping;
@property (nonatomic, copy) NSString *sourceKeyPath;
@property (nonatomic, copy) NSString *destinationKeyPath;
+ (PropertyMapping *)propertyMappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath withMapping:(ObjectMapping *)mapping;
@end
#import "PropertyMapping.h"
@implementation PropertyMapping
+ (PropertyMapping *)propertyMappingFromKeyPath:(NSString *)sourceKeyPath toKeyPath:(NSString *)destinationKeyPath withMapping:(ObjectMapping *)mapping
{
PropertyMapping *propertyMapping = [self new];
propertyMapping.sourceKeyPath = sourceKeyPath;
propertyMapping.destinationKeyPath = destinationKeyPath;
propertyMapping.objectMapping = mapping;
return propertyMapping;
}
@end
ObjectMapping
ObjectMapping管理整个Object的PropertyMapping,包括objectClass,propertyMappings。并且提供Object反映射的inverseMapping。
#import <Foundation/Foundation.h>
@class PropertyMapping;
@interface ObjectMapping : NSObject
- (ObjectMapping *) initWithClass:(Class) objectClass;
- (ObjectMapping *) inverseMapping;
- (void) addPropertyMapping:(PropertyMapping *) porpertyMapping;
//add simple propertys
- (void) addPropertyMappingsFromDictionary:(NSDictionary *) dic;
@end
#import "ObjectMapping.h"
@interface ObjectMapping ()
@property (nonatomic, readwrite) Class objectClass;
@property (nonatomic, readwrite) NSMutableArray *propertyMappings;
@property (nonatomic, readwrite) NSMutableArray *mappedKeyPaths;
@end
@implementation ObjectMapping
+ (instancetype)mappingForClass:(Class)objectClass
{
return [[self alloc] initWithClass:objectClass];
}
- (id)initWithClass:(Class)objectClass
{
self = [super init];
if (self)
{
self.objectClass = objectClass;
self.propertyMappings = [NSMutableArray new];
self.mappedKeyPaths = [NSMutableArray new];
}
return self;
}
- (void)addPropertyMapping:(PropertyMapping *)porpertyMapping
{
NSAssert([self.map