我建议一个不同的设计。发出请求的东西应该是任何 VC 都可以实例化并用来发出请求的类,可能是 NSURLRequest 的子类。
因为它是一个单例,所以很容易让应用程序委托一个全局数据和行为的持有者,但这不是它的工作。
如果你对服务器请求有很多自定义工作要做,请子类化 NSURLRequest。使用 NSURLConnection 的 sendAsynchronousRequest: 方法运行它。它允许调用者在完成时传递一个块以执行请求结果。
例如 MyRequest.h
@interface MyRequest : NSMutableURLRequest
- (id)initWithParams:(NSDictionary *)params;
- (void)runWithCompletion:(void (^)(id result, NSError *error))completion;
@end
例如 MyRequest.m
@implementation MyRequest
- (id)initWithParams:(NSDictionary *)params {
self = [self init];
if (self) {
// do custom init here, e.g.
self.URL = @"http://www.myservice.com/myrequest.json"
[self setValue:@"bar" forHTTPHeaderField:@"foo"]; // more realistically, using key value pairs in the params dictionary
// and so on
}
return self;
}
- (void)runWithCompletion:(void (^)(id result, NSError *error))completion {
[NSURLConnection sendAsynchronousRequest:self
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data) {
// do something custom with the received data here,
// like convert to a string and parse as json, etc.
completion(data, nil);
} else {
completion(nil, error);
}
}];
}
@end
现在,任何 VC——或任何其他类——都可以创建其中一个并使用它:
// in MyVC.m
MyRequest *myRequest = [[MyRequest alloc] initWithParams:[NSDictionary dictionary]];
[myRequest runWithCompletion:^(id result, NSError *error) {
// do main thread ui stuff with the result in hand, e.g.
[self.tableView reloadData];
}];