0

我正在使用 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 为零。为什么会这样?

4

1 回答 1

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];
    }];
于 2013-04-12T04:10:38.840 回答