0

我是使用 RestKit 的新手,但我完全不明白它是如何工作的......拜托,可以在某个地方解释一下吗?

我的 Json 文件是:

    {
    "colors":
    {
        "red":"#f00",
        "green":"#0f0",
        "blue":"#00f",
        "cyan":"#0ff",
        "magenta":"#f0f",
        "yellow":"#ff0",
        "black":"#000"
    }
}

我托管此文件的路径是:http://186.36.181.116/tesis/file.json

我在 ViewDidLoad 方法中尝试的代码是:

    - (void)viewDidLoad
{
    [super viewDidLoad];

    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[colores class]];
    [mapping addAttributeMappingsFromArray:@[@"colors"]];
    NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // Anything in 2xx
    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:@"/tesis/:coloresID" keyPath:@"colors" statusCodes:statusCodes];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://186.36.181.116/tesis/file.json"]];
    RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[responseDescriptor]];
    [operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
        colores *colores = [result firstObject];
        NSLog(@"Mapped the article: %@", colores);
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        NSLog(@"Failed with error: %@", [error localizedDescription]);
    }];
    [operation start];
}

我的班级“颜色”如下:

#import <Foundation/Foundation.h>
@interface colores : NSObject{}
@property (weak, nonatomic) IBOutlet NSString *colores;
@end

非常感谢你!

4

1 回答 1

0

你可以在这里找到详细的教程和完整的源代码github

为了正确地将响应映射到 JSON,我们必须执行以下操作:

*为我们的托管对象模型中的每个实体创建一个 RKEntityMapping 实例
*在 JSON 响应键和对象属性
之间添加映射 *在嵌入式 JSON 对象和关系之间添加映射
*使用映射创建响应描述符
*可选:使用映射创建请求描述符,如果你打算 PUT 或 POST

于 2013-10-22T04:38:30.980 回答