LoginSignup
16
15

More than 5 years have passed since last update.

RestKit使ったデータ取得

Posted at

概要

  • ObjectManagerというにdescriptorを追加して利用する。
  • descriptorには、どのパスから受け取ったデータをどうモデルにマッピングするかを定義している

ObjectManagerにdescriptorを追加

  • RKObjectManagerを継承したオブジェクト(ex. WTDObjectManager)をinitするタイミングで、descriptorを追加している。
- (instancetype)init
{
    self = [super initWithHTTPClient:[AFHTTPClient new]];
    if (self) {
        // add descriptor
    }
    return self;
}
  • descriptorには、addResponseDescriptorsFromArrayaddRequestDescriptorsFromArrayがあって、前者が受け取るデータを後者が送信するデータをマッピングしている。
[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については、モデルに定義すると分かりやすい。RKObjectMappingmappingForClassを利用する。
@implementation User

+ (RKObjectMapping *)responseMapping
{
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[self class]];
    [mapping addAttributeMappingsFromDictionary:@{
                                                  @"id":                           @"userID",
                                                  @"name":                         @"name",
                                                  }];
    return mapping;
}

@end

参考ページ

16
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
15