Wrapping blocks based API in convenience methods

你离开我真会死。 提交于 2019-12-11 23:13:56

问题


I'm using AFNetworking 2.0 to access a web api (although this would apply to NSURLSession as well), and currently I have a bunch of code that looks like this:

[self.rottenTomatoesManager GET:@"movies.json" parameters:@{@"q" : searchString, @"apikey" : [self.rottenTomatoesManager apiKey]}
                                success:^(NSURLSessionDataTask *task, id responseObject) {
                                    NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
                                    if(response.statusCode == 200){
                                        NSDictionary *responseData = responseObject;
                                        self.searchResults = responseData[@"movies"];
                                        [self.searchDisplayController.searchResultsTableView reloadData];
                                        [self.tableView reloadData];
                                    }
        }
                                failure:^(NSURLSessionDataTask *task, NSError *error) {
                                    NSLog(@"Error loading movies %@", error.localizedDescription);
        }];

I'd like to take that functionality and wrap it in a convenience method that looks something like this

NSArray *results = [self.rottenTomatoesManager searchMoviesWithTitle:@"The avengers"]

to clean up the ViewController code and to make most of the code framework agnostic.

What is the best way to do this so that I'm not turning a nice asynchronous blocks based API into a synchronous API?


回答1:


Callback blocks are great for this.

[self loadSomethingWithCallback:^(NSArray *results) {
    NSLog(@"%@", results);
}];


来源:https://stackoverflow.com/questions/24253207/wrapping-blocks-based-api-in-convenience-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!