异步函数不返回数据

时间:2015-05-30 17:32:36

标签: objective-c asynchronous afnetworking afnetworking-2

我写了一个函数来从URL中获取NSDictionary

[Data loadFromAPI:@"http://example.com/api" withSuccess:^(id data) {
    NSMutableDictionary *result = (NSDictionary *)data;

    CLS_LOG(@"result: %@", result);
} failure:^(NSError *error) {
    CLS_LOG(@"Error: %@", error);
}];

它调用的函数如下:

typedef void (^Success)(id data);
typedef void (^Failure)(NSError *error);

+ (void)loadFromAPI:(NSString *)apiURL withSuccess:(Success)success failure:(Failure)failure {
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:apiURL]];

    NSMutableURLRequest *mutableRequest = [request mutableCopy];

    request = [mutableRequest copy];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [JSONResponseSerializerWithData serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSArray *jsonArray = (NSArray *)responseObject ;

        NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:
                               [self now], @"time",
                               jsonArray, @"response",
                               nil];

        CLS_LOG(@"Result is: %@", result);

        success(result);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure?failure(error):nil;
    }];

    [operationQueue setMaxConcurrentOperationCount:1];
    [operationQueue addOperations:@[operation] waitUntilFinished:NO];
}

函数CLS_LOG(@"Result is: %@", result);内部返回返回的数据。但是,我调用函数CLS_LOG(@"result: %@", result);的地方会返回null。我做错了什么?

2 个答案:

答案 0 :(得分:0)

事实证明$(document).ready(function() { $("body").on("click", ".slide", function(e) { e.preventDefault(); var url = $(this).attr('data-url') + ' #' + $(this).attr('data-target'); $('.tile-area-main').load(url); }); }); 返回了[self now],因此null未正确设置。

答案 1 :(得分:0)

问题是

NSMutableDictionary *result = (NSDictionary *)data;

你不能直接这样做,我想知道为什么你没有这个警告......

NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithDictionary:(NSDictionary *)data];

可能会解决问题...