多线程目标-c

时间:2016-07-18 07:14:09

标签: objective-c multithreading

我必须使用从iphone的键盘输入的关键字搜索数据库。 当我搜索键盘停止时。如果我在后台运行,那么我找到一个空数组。 我想要两个键盘,以便键盘不会停止,等到阵列充满数据。我正在使用objective-c。

dispatch_semaphore_t task = dispatch_semaphore_create(0);

manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    if (error) {

    } else {
        //int i=0;
        //NSLog(@"%@",responseObject);

         header=responseObject;


        dispatch_semaphore_signal(task);

    }

}];

[dataTask resume];


dispatch_semaphore_wait(task, DISPATCH_TIME_FOREVER);
return header;

1 个答案:

答案 0 :(得分:1)

您采用了一种固有的异步方法dataTaskWithRequest,并使其同步(即它阻止了调用它的线程)。摆脱所有那些信号量的东西。无论如何,这是一个非常糟糕的模式。

我认为你这样做是因为你想从网络电话中获取return数据。你不应该这样做。您应该使用完成处理程序模式,例如

例如,让我们假设您的方法目前看起来像:

- (id)performRequest:(NSURLRequest *)request {
    __block id header;

    manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {

        } else {
            header = responseObject;
        }
        dispatch_semaphore_signal(semaphore);
    }];

    [dataTask resume];

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    return header;
}

您应该将其更改为void返回类型,并添加completionHandler参数:

- (void)performRequest:(NSURLRequest *)request completionHandler:(void (^)(id _Nullable responseObject, NSError * _Nullable error))completionHandler {
    manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            completionHandler(nil, error);
        } else {
            completionHandler(responseObject, nil);
        }
    }];

    [dataTask resume];
}

你可以这样称呼它:

[self performRequest:request completionHandler:^(id responseObject, NSError *error) {
    // use responseObject and error here
}];

// but not here