我正在编写一个查询 XML REST Web 服务的小型 iOS 应用程序。使用的网络框架是AFNetworking。
情况
要查询 Web 服务,我将 AFHTTPClient 子类化:
@interface MyApiClient : AFHTTPClient
在实现中,我将其作为单例提供:
+ (MyApiClient *)sharedClient {
static MySharedClient *_sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseUrl:[NSUrl URLWithString:@"http://url.to.the.webservice"]];
});
return self;
}
在 initWithBaseURL 我告诉 AFNetworking 期待 XML 内容:
[self registerHTTPOperationClass:[AFXMLRequestOperation class]];
现在我可以从我的 ViewController 对单例调用 getPatch 并在成功块中开始解析我返回的 XML。然后,在 ViewController 中的 NSXMLParserDelegate 方法中,我可以选择我感兴趣的 XML 部分并对其进行处理。
问题
我想在我的 HTTPClient 单例中有方法来处理与 web 服务相关的所有内容并返回数据模型或模型列表而不是 XML。
例如我想做这样的事情:
ServerModel *status = [[MyApiClient sharedClient] getServerStatus];
然后,ApiClient 将在内部调用 Web 服务,解析 XML 并返回模型。我怎样才能做到这一点?通常我会使用一个在解析 XML 后被调用的委托,但是由于 ApiClient 的单例性质,可能有多个委托?
希望有人能解释一下,谢谢!