Search code examples
iphoneobjective-cios6

asynchronous data load iOS


I have a list of loaded image in my application with LazyLoader, I want to update this list when I add an image in the database. I use NSURLConnection to load images


Solution

  • IMHO, the easiest option would be to put your code in a block and let it be executed asynchronously. That way you keep a simple flow.

    To that end, use:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
    ^{
    
        // INSERT YOUR CODE HERE
        // Whatever you put in here will be executes asynchronously.
    });
    

    Edit in response to OP's comments:

    NSURLConnection's method:

    - (id)initWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate
    

    can't be used. According to the documentation:

    The delegate object for the connection. The delegate will receive delegate messages as the load progresses. Messages to the delegate will be sent on the thread that calls this method. By default, for the connection to work correctly, the calling thread’s run loop must be operating in the default run loop mode. See scheduleInRunLoop:forMode: to change the run loop and mode.

    The solution is to use:

    + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
    

    No special threading or run loop configuration is necessary in the calling thread in order to perform a synchronous load.

    Or to use:

    + (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
    

    with a block completion handler.

    Notes:
    If the task to perform are only to be done after the request is done (e.g. calling a delegate), then sendAsynchronousRequest:queue:completionHandler: is the best option.