Wrapping blocks based API in convenience methods

2019-08-28 23:54发布

问题:

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);
}];