一个类别,用于将对象字典表示形式的值映射到对象的属性。
NSObject+DHNObjectMapping默认通过使用键值编码将字典表示形式的关键字映射到数据对象的属性。如果您的数据对象有一个与字典表示形式中的关键字相同名称的属性,则其值会映射到数据对象的属性上。
NSDictionary representation -> Class object
{"name":"This is some name"} -> object.name
默认情况下忽略未定义的键。
您可以通过覆盖数据中的dhn_updatePropertiesWithDictionary:andConfiguration:
方法来实现其他行为。有关更多信息,请参阅覆盖默认映射行为。
因此,您只需处理对象的特殊映射。
将以下行添加到您的Podfile中。
pod 'DHNObjectMapping', :git => 'https://github.com/dreyhomedev/NSObject-DHNObjectMapping.git'
您也可以手动添加NSObject+DHNObjectMapping.h
和NSObject+DHNObjectMapping.m
。
由于NSObject+DHNObjectMapping是与NSDictionary一起工作的,因此我们需要将对象数据转换为NSDictionary表示形式。有许多方法可以实现这一点。这取决于您使用的数据格式。对于JSON或Plist文件,Cocoa提供了序列化器为您完成这项工作。如果您使用自己的特殊数据格式,需要先将这些数据转换为NSDictionary表示形式。
要将数据映射到您的Cocoa对象,只需使用该对象的NSDictionary表示形式调用dhn_objectWithDictionary:
。如果您有一个要映射的类的字典表示形式的数组,只需调用dhn_arrayOfObjectsWithArray:
。它还适用于Core Data对象,只需调用dhn_objectWithDictionary:inManagedObjectContext:
并提供您的NSManagedObjectContext。
要覆盖标准的映射行为,您可以在数据类中重写dhn_updatePropertiesWithDictionary:andConfiguration:
。此方法将提供一个DHNObjectMappingConfiguration
,您可以按需调整它。在指定完映射后,只需调用[super dhn_updatePropertiesWithDictionary:andConfiguration:]
。
DHNObjectMappingConfiguration
类提供了通过设置新的字典键属性映射、设置映射嵌套字典表示的形式或针对特殊处理设置类的方法来更改默认映射的功能。
#import "NSObject+DHNObjectMapping.h"
...
- (void)dhn_updatePropertiesWithDictionary:(NSDictionary *)dictionary andConfiguration:(DHNObjectMappingConfiguration *)mappingConfiguration
{
[mappingConfiguration setMappingFromDictionaryKeyPath:@"someKey" toPropertyKey:@"mappToMe"];
[mappingConfiguration setMappingFromDictionaryKeyPath:@"someOtherKey"
toPropertyKey:@"someOtherProperty"
withBlock:^id(NSString *propertKey,
NSString *dictionaryKey,
id dictionaryData) {
id someValueObject = nil;
// ... Do you’re mapping and return
// The value the property should have
// Return kDHNMappingByDefault to use the default behavior
return someValueObject;
}];
[mappingConfiguration setMappingFromDictionaryKeyPath:@"anotherKey"
toPropertyKey:@"aPropertyOfClassMyClass"
withClass:[MyClass class]];
[mappingConfiguration setMappingForDictionaryKeyPath:@"whatAKey"
withBlock:^(NSString *dictionaryKeyPath,
id dictionaryData) {
// ... Do your mapping and assign your values to all properties you like
// This block is not bound to any property of self.
}];
[super dhn_updatePropertiesWithDictionary:dictionary andConfiguration:mappingConfiguration];
}
由于使用了键值编码,直接映射标量值属性(例如:类型为 BOOL、NSInteger、float 等)是不可能的。