Question

My app fetches some items from web server like below:

for (photo in photoList) {
    NSArray *comment = [self fetchCommentsFromServer:photo.photoId];
    [photo setComment:comment];
}

fetchCommentFromServer makes asynchronous http call with dispatch_async.

dispatch_queue_t queue = dispatch_queue_create("autantication_queue", 0);
dispatch_async( queue, ^{

    [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        if (success) {
            success(responseObject);
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }

    }
     ];
});

It gives error because of comment isn't ready when I try to attach it to photo. How can I guarantee that the comment is ready when it's attached to photo?

I tried to use semaphores but it made the call too slow.

Was it helpful?

Solution 2

The method you call to get the data executes then the next line sets the message without the response coming back. You should modify fetchCommentsFromServer to have a completion block where you then set the comment inside the block (ensuring the request has completed before trying to modify it).

On a side note, make sure to jump back on the main thread to modify any UI elements (AKA your label).

OTHER TIPS

fetchCommentsFromServer needs a completion block. This can be executed whenever the network call has finished. Alternatively, you can work on each photo after the fetch is complete, as part of the network call completion block.

The only way you can guarantee the network fetch is finished when you want to work on the results is to not try and do any work until the network fetch is finished. This is pretty much the point of all these completion blocks and delegate methods.

fetchCommentsFromServer: can't return anything because the data that it wants to return isn't available until after the method has completed. Instead, the method should take a completion block as a parameters and pass the data back using that. In your case, this will be called from the AFNetworking success block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top