我正在使用AFNetworking来获取数据,我在Service类中有一个委托,它可以是一个UIController。 Service类负责通过AFNetworking类获取数据。
//Class Service.
@interface Service : NSObject {
__weak id<ServiceDelegate>delegate;
}
- (void) doFetch:(APIInput*) input {
NSURL *url = [NSURL URLWithString:[self getLocation:input]];
NSLog(@"url request is: %@", url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"origin"]);
[self.delegate serviceDidComplete:[self allocNewData:JSON]];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
NSError *error, id JSON){
[self.delegate serviceFailed: error];
}];
[operation start];
}
在UIController viewDidLoad中:我有以下
self.networkService = [[Service alloc] init];
[self.networkService setDelegate:self];
一旦我运行ios应用程序,self.delegate就是零。为什么会这样?
答案 0 :(得分:4)
这解决了它。我在设置操作
之前创建了一个__block变量__block id itsme = self.delegate;
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"origin"]);
[itsme serviceDidComplete:[self allocNewData:JSON]];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response,
NSError *error, id JSON){
[itsme serviceFailed: error];
}];