RestKit 是一個 open source 的 Objective-C 套件,支援 iOS 與 Mac OS X。
https://github.com/RestKit/RestKit
RestKit 幾乎完整包裝了所謂 MVVM 架構中的 VM,只要做些微調整,便可以輕易將 RESTful 的 API 轉換成 Objective-C 中的 Models。跟 Core Data 也進行了高度整合。
在 RestKit 中,只需要透過 RKObjectMapping,便可以將 API 回來的結果轉換成你所指定的 Model,這是一個簡單的範例,
有一個 Model - User 結構如下
@interface User : NSObject
@property (nonatomic, copy) NSNumber *userID;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *screenName;
@end
NSURL *baseURL = [NSURL URLWithString:@"http://[API HOST]"];
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:baseURL];
RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[User class]];
[userMapping addAttributeMappingsFromDictionary:@{@"id" : @"userID", @"screen_name" : @"screenName", @"name" : @"name"}];
[{
"user": {
"id": 31337,
"name": "Blake Watters",
"screen_name": "Blake Watters"
}
}]
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:userMapping
method:RKRequestMethodGET
pathPattern:@"[API URL pattern]"
keyPath:nil
statusCodes:[NSIndexSet indexSetWithIndex:200]
];
[objectManager addResponseDescriptor:responseDescriptor];
[objectManager getObjectsAtPath:@"[User API URL]" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
// success
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
// failure
}];