Search code examples
iosblock

Passing an object into a ASIHTTPRequest block


OK. I'm not completely clear about blocks, but I do use them often; especially when doing an ASIHTTPRequest. I'd like to pass an object into the block and have the request assign a value to the object on completion, but I don't know how to make the object 'available' inside a block.

Here's my method...

- (void)fetchImageAsynchronously:(NSURL *)theURL intoImageObject:(UIImage *)anImageObject
{
    __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:theURL];
    [request setDownloadCache:[ASIDownloadCache sharedCache]];
    [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
    [request setCompletionBlock:^{
        NSData *responseData = [request responseData];
        anImageObject = [UIImage imageWithData:responseData];
    }];
    [request setFailedBlock:^{
        // NSError *error = [request error];
    }];
    [request startAsynchronous];
}

So, when the request completes, I want the value of anImageObject to be the fetched image. But anImageObject is not available inside the block.

Would someone kindly help?


Solution

  • anImageObject would have to be passed by reference. That is, UIImage**, and pass the address of anImageObject when calling the method.

    This isn't a great design because you'll also have to manage the lifetime of anImageObject and also likely post some sort of notification that it is ready. That is, this code will break if anImageObject is deallocated in the time that it takes to download the image data. And you wont know that anImageObject was initialized with data or not.

    - (void)fetchImageAsynchronously:(NSURL *)theURL intoImageObject:(UIImage **)anImageObject
    {
        __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:theURL];
        [request setDownloadCache:[ASIDownloadCache sharedCache]];
        [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
        [request setCompletionBlock:^{
            NSData *responseData = [request responseData];
            *anImageObject = [UIImage imageWithData:responseData];
        }];
        [request setFailedBlock:^{
            // NSError *error = [request error];
        }];
        [request startAsynchronous];
    }