NSOperation

Lets say you are not only downloading tweets (text) from the web, but actual chunks of raw data, such as images. You may have a method that returns a UIImage, such as:

-(UIImage*)cachedImageForURL:(NSURL*)url{
//Preferably look for a cached image
id cachedObject = [cachedImages objectForKey:url];
if (cachedObject == nil)
{
//set loading placeholder in our cache dict
[cachedImages setObject:LoadingPlacedholder forKey:url];
//Create and queue a new image loading op
ImageLoadingOp *operation = [[ImageLoadingOp alloc] initWithImageURL:url target:self action:@selector(didFinishLoadingImageWithResult:)];
[operationQueue addOperation:operation];
[operation release];
} else if(![cachedObject isKindOfClass:[UIImage class]])
{
//were already loading the image, dont kick off another request
cachedObject = nil;
}
return cachedObject;
}

Except notice this time the operation is not an NSInvocationOperation but rather a Class by itself. That class is responsible for downloading the image from the web, processing it, returning it and caching it.

Upon your return you do this:

-(void)didFinishLoadingImageWithResult:(NSDictionary*)result{
NSURL *url = [result objectForKey:@”url”];
UIImage *image = [result objectForKey:@”image”];
[cachedImages setObject:image forKey:url];
[self.tableView reloadData];
}

Leave a Reply