如何在iOS中使用RestKit 2.X?

时间:2013-10-22 04:02:50

标签: ios objective-c json restkit restkit-0.20

我是使用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];
}

我的班级“colores”如下:

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

提前非常感谢!!

1 个答案:

答案 0 :(得分:0)

您可以找到详细的教程here和完整的源代码github

为了正确映射对JSON的响应,我们必须做以下事情:

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

,请使用映射创建请求描述符