1

I'm writing a ios app which has to send and receive data from the API at various screens in the app. Currently each view controller is calling this code

// AFAppDotNetAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates
[[AFAppDotNetAPIClient sharedClient] getPath:@"stream/0/posts/stream/global" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) {
    NSLog(@"App.net Global Stream: %@", JSON);
} failure:nil];

I want to keep things DRY and so I created a requested builder and response handler to create request and parse responses. I also want to move all the API calls to one class but since it uses blocks I don't know how do this.

Can someone explain how this is done so I call one method with a enum and some params for request and I probably just get a NSDictionary back without having API calls and blocks in all view controllers. Thanks

4

2 回答 2

1

这是 MVC 架构的模型部分的一个问题。示例项目对此有很好的实现:

Post.h

+ (void)globalTimelinePostsWithBlock:(void (^)(NSArray *posts, NSError *error))block;

在模型上定义负责发出请求(将任何方法参数转换为请求参数)和从响应中序列化对象的类方法。

于 2013-08-26T21:35:35.813 回答
0

定义你的新接口以包括你的枚举、参数和一个块。将块定义为具有BOOL(状态)和NSDictionary(结果)。这基本上只是将接口从客户端、路径和操作中简化和抽象出来。然后在successandfailure块中,您可以使用适当的参数调用外部块。

该块需要保持接口的异步特性。您可以使用目标和选择器,但这将是更多代码且不太灵活。您不能让该方法只返回结果字典。

对于将哪些参数传递给方法和块,显然还有许多其他选项。

于 2013-08-26T10:46:27.420 回答