-
Notifications
You must be signed in to change notification settings - Fork 2
Adapters
Fabian edited this page Feb 24, 2015
·
3 revisions
You can pass a dictionary of blocks for field requiring special handling. Say a service sends back a dictionary that looks something like this:
{
"favorite_color": [
122,
50,
80
],
"least_favorite_color": [
121,
51,
81
]
}
and we expect to map it to a model like this
@interface MYModel : NSObject
@property (nonatomic, strong) UIColor *favoriteColor;
@property (nonatomic, strong) UIColor *leastFavoriteColor;
@end
You can adapt the response with an adapter block:
OHMMappable([MYModel class]);
OHMSetMapping([MYModel class], @"least_favorite_color" : @"leastFavoriteColor", @"favorite_color" : @"favoriteColor")
OHMValueAdapterBlock colorFromNumberArray = ^(NSArray *numberArray) {
return [UIColor colorWithRed:[numberArray[0] integerValue]/255.0
green:[numberArray[1] integerValue]/255.0
blue:[numberArray[2] integerValue]/255.0
alpha:1];
};
OHMSetAdapter([MYModel class], @{@"favoriteColor": colorFromNumberArray, @"leastFavoriteColor": colorFromNumberArray});
Note that the key for the adapter is the key on the model object, not on the response. And adapters are added for a property, not a type. If the above example had multiple properties that were colors, you would have to set an adapter block for each property. It would be smart to reuse adapter blocks in your code.
The OHMValueAdapterBlock
type is a block that takes an id
and returns an id
. i.e typedef id(^OHMValueAdapterBlock)(id);