//Create a block operation for loading the image into the profile image view NSBlockOperation *loadImageIntoCellOp = [[NSBlockOperation alloc] init]; //Define weak operation so that operation can be referenced from within the block without creating a retain cycle __weakNSBlockOperation *weakOp = loadImageIntoCellOp; [loadImageIntoCellOp addExecutionBlock:^(void){ //Some asynchronous work. Once the image is ready, it will load into view on the main queue UIImage *profileImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:friend.imageUrl]]]; [[NSOperationQueue mainQueue] addOperationWithBlock:^(void) { //Check for cancelation before proceeding. We use cellForRowAtIndexPath to make sure we get nil for a non-visible cell if (!weakOp.isCancelled) { FacebookFriendCell *theCell = (FacebookFriendCell *)[tableView cellForRowAtIndexPath:indexPath]; [theCell.ivProfile setImage:profileImage]; [self.facebookUidToImageDownloadOperations removeObjectForKey:friend.uid]; } }]; }];
//Save a reference to the operation in an NSMutableDictionary so that it can be cancelled later on if (friend.uid) { [self.facebookUidToImageDownloadOperations setObject:loadImageIntoCellOp forKey:friend.uid]; }
//Add the operation to the designated background queue if (loadImageIntoCellOp) { [self.imageLoadingOperationQueue addOperation:loadImageIntoCellOp]; }
//Make sure cell doesn't contain any traces of data from reuse - //This would be a good place to assign a placeholder image cell.ivProfile.image = nil;