概要
- ObjectManagerというにdescriptorを追加して利用する。
- descriptorには、どのパスから受け取ったデータをどうモデルにマッピングするかを定義している
ObjectManagerにdescriptorを追加
-
RKObjectManager
を継承したオブジェクト(ex.WTDObjectManager
)をinitするタイミングで、descriptorを追加している。
- (instancetype)init
{
self = [super initWithHTTPClient:[AFHTTPClient new]];
if (self) {
// add descriptor
}
return self;
}
- descriptorには、
addResponseDescriptorsFromArray
とaddRequestDescriptorsFromArray
があって、前者が受け取るデータを後者が送信するデータをマッピングしている。
[self addResponseDescriptorsFromArray:@[]];
[self addRequestDescriptorsFromArray:@[]];
descriptorの作り方
- descriptorの作り方は、以下のようにマッピングのルールとリクエストのmethodとpathとkeyPathとstatusCodeを設定する。
[RKResponseDescriptor responseDescriptorWithMapping:responseMapping
method:RKRequestMethodGET
pathPattern:kAPIPath
keyPath:kAPIResponseKeyPath
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]
- keyPathは、以下のようなuser jsonをuser modelにマッピングするとき、
data
と設定する
{
data: {
user : {
id : "1",
name: "rei kubonaga",
}
}
}
- mappingについては、モデルに定義すると分かりやすい。
RKObjectMapping
のmappingForClass
を利用する。
@implementation User
+ (RKObjectMapping *)responseMapping
{
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[self class]];
[mapping addAttributeMappingsFromDictionary:@{
@"id": @"userID",
@"name": @"name",
}];
return mapping;
}
@end