Skip to content

Instantly share code, notes, and snippets.

@bromanko
Created December 26, 2011 03:24
Show Gist options
  • Save bromanko/1520474 to your computer and use it in GitHub Desktop.
Save bromanko/1520474 to your computer and use it in GitHub Desktop.
GCD Implementation
- (AQGridViewCell *)gridView:(AQGridView *)gridView cellForItemAtIndex:(NSUInteger)index {
switch ([self numberOfItemsInGridView:gridView] - index) {
case 2:
// Favorites cell
return [TopicListViewController favoritesCell];
case 1:
// Add cell
return [TopicListViewController addCell];
default: {
// Topic cells
static NSString *topicCellIdentifier = @"TopicCell";
SubscribedTopic *subscribedTopic = [self.subscribedTopics objectAtIndex:(NSUInteger) index];
TopicGridViewCell *cell = (TopicGridViewCell *) [gridView dequeueReusableCellWithIdentifier:topicCellIdentifier];
if (cell == nil) {
cell = [[[TopicGridViewCell alloc] initWithFrame:TopicGridCellRect reuseIdentifier:topicCellIdentifier] autorelease];
}
cell.topic = [subscribedTopic BBStackAPISite];
[self getQuestionCountForCell:cell index:index];
return cell;
}
}
}
- (void)getQuestionCountForCell:(TopicGridViewCell *)cell index:(NSUInteger)index {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0ul);
dispatch_async(queue, ^{
sleep(2 * index);
CachingStackExchangeAPIClient *apiClient = [[CachingStackExchangeAPIClient alloc] initWithDatabase:self.cacheDatabase
site:cell.topic];
[apiClient getStats:^(BBStackAPICallData *callData, NSArray *results) {
BBStackAPISiteStatistics *stats = [results objectAtIndex:0];
cell.questionCount = stats.totalQuestions;
} failure:nil];
[apiClient release];
});
}
@bromanko
Copy link
Author

So we dequeue the cell like normal and set properties for things we already have. For the background loaded content, I use GCD to queue up a background task. In my async block I just sleep for a bit (I scale the sleep based on the index of the cell...probably a naive implementation) and then make the API request.

Normally you need to run the UI updating code (cell.questionCount = stats.totalQuestions) back in the UI thread but I noticed that AFNetworking does that already in the success block. Super clean and seems to work really well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment