Synchronizing data in UITableView with TWRequest in iOS5-Collection of common programming errors

I’ve been trying to work with TWrequest and retrieve a block of Tweets but I’m running into problems keeping the data synchronized and update the tableview.

I have the following relatively simple block in the TableViewController to get the users account information :

- (void)viewDidLoad
{
  NSArray *twitterAccounts = [[NSArray alloc] init];    
  if ([TWRequest class]) {        
    store = [[ACAccountStore alloc] init];
    ACAccountType *twitterType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [store requestAccessToAccountsWithType:twitterType withCompletionHandler:^(BOOL granted, NSError *error){
        if (granted == YES) {
            NSLog(@"Access granted to Twitter Accounts");
        } else {
            NSLog(@"Access denied to Twitter Accounts");
        }
    }];       
    twitterAccounts = [store accountsWithAccountType:twitterType];
    self.account = [[store accounts] objectAtIndex:0];
  } else {
    // The iOS5 Twitter Framework is not supported so need to provide alternative
  }

  self.homeTimeLineData = [NSMutableArray array];
  self.profileImages = [NSMutableDictionary dictionary];
  [self updateTimeLineData:HOME_TIMELINE_URL];
  [super viewDidLoad];
}

fetch the latest 20 tweets from the users home timeline:

- (void)updateTimeLineData:(NSString *)urlString {

  NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"20", @"count", nil];    
  TWRequest *myHomeTimeLine = [[TWRequest alloc] initWithURL:[NSURL URLWithString:urlString] parameters:parameters requestMethod:TWRequestMethodGET];
  myHomeTimeLine.account = account;

  [myHomeTimeLine performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {    
    NSError *jsonError = nil;
    NSArray *timeLineData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonError];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self refresh:timeLineData]; 
    }); 
  }];    
}

parse the timeline data and reload the tableview :

- (void)refresh:(NSArray *)arrayOfTweets {

  for (int i=0; i < [arrayOfTweets count]; i++) {       
    NSDictionary *rawTweetJSON = [arrayOfTweets objectAtIndex:i];

    Tweet *tweet = [[Tweet alloc] init];
    tweet.screenName = [[rawTweetJSON objectForKey:@"user"] objectForKey:@"screen_name"];
    tweet.tweetText = [rawTweetJSON objectForKey:@"text"];
    tweet.createdAt = [rawTweetJSON objectForKey:@"created_at"];

    [self.homeTimeLineData insertObject:tweet atIndex:i];
  }

  [self.tableView reloadData];    
}

This works fine but each time I try to make a variation on this I run into problems

  1. If I try to parse the JSON date in the performRequestWithHandler block and pass back the parsed data, I get an assertion failure.
  2. If I move the request for access to the accounts to the AppDelegate (so that the accounts information can eventually be shared between different view controllers) and pass the account I need to the TableViewController, I get an assertion failure.

In both cases the assertion failure appears to be the same : the tableview will update enough tweets to fill the screen the first time then it will make a call to tableView:numberOfRowsInSection: and after the data for the next cell is null.

2011-11-23 00:02:57.470 TwitteriOS5Tutorial[9750:10403] * Assertion failure in -[UITableView _createPreparedCellForGlobalRow:withIndexPath:], /SourceCache/UIKit_Sim/UIKit-1912.3/UITableView.m:6072

2011-11-23 00:02:57.471 TwitteriOS5Tutorial[9750:10403] * Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:’

I’ve tried looking at other similar questions but I couldn’t understand how to keep the different blocks in sync. What struck me as odd is the impact of where the request for account information is located.

homeTimeLineData in this case is just an NSMutableArray. Is the solution to go to Core Data and use an NSFetchResultsController?

My knowledge of blocks is still a little limited so any insights would be greatly appreciated. Thanks, Norman

Update :

I believe I found the problem, it is related to Storyboards and TableViewCells.

In a tutorial on Storyboards I followed it said you could replace

NSString *CellIdentifier = @"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

with a single line

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];

and the Storyboard would take care of creating a new copy of the cell automatically if there was not one to dequeue. I checked the Apple documentation and it says this also.

I followed this advice and used just the single line declaration and it worked up to a point but then as I was refactoring and rearranging the code I started to get the assertion failures.

I am using a custom UITableViewCell with IBOutlets to reposition different elements within the cell so it may be a limitation that to remove the lines that “check the return value of the cell” you have to stick with standard cells and do all your customization within the storyboard and Interface Builder.

Has anyone run into a similar problem?

  1. I guess you’re using ARC. Make sure you hold on to the AccountStore, e.g. by declaring a strong property like this:

    // AccountsListViewController.h
    @property (strong, nonatomic) ACAccountStore *accountStore;
    

    You can then use this list to fetch the list of accounts on your device:

    // AccountsListViewController.m
    - (void)fetchData
    {
        if (_accounts == nil) {
            if (_accountStore == nil) {
                self.accountStore = [[ACAccountStore alloc] init];
            }
            ACAccountType *accountTypeTwitter = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
            [self.accountStore requestAccessToAccountsWithType:accountTypeTwitter withCompletionHandler:^(BOOL granted, NSError *error) {
                if(granted) {
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        self.accounts = [self.accountStore accountsWithAccountType:accountTypeTwitter];
                        [self.tableView reloadData]; 
                    });
                }
            }];
        }
    }
    

    As soon as the user selects one of the accounts, assign it to the view controller you’ll be using to display the list of tweets:

    // AccountsListViewController.m
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        TweetsListViewController *tweetsListViewController = [[TweetsListViewController alloc] init];
        tweetsListViewController.account = [self.accounts objectAtIndex:[indexPath row]];
        [self.navigationController pushViewController:tweetsListViewController animated:TRUE];
    }
    

    Now, in TweetListViewController, you need to hold on to the account in a strong property, just like this:

    // TweetListViewController.h
    @property (strong, nonatomic) ACAccount *account;
    @property (strong, nonatomic) id timeline;
    

    And finally fetch the tweets in your view like this:

    // TweetListViewController.m
    - (void)fetchData
    {
        NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1/statuses/home_timeline.json"];
        TWRequest *request = [[TWRequest alloc] initWithURL:url 
                                                     parameters:nil 
                                                  requestMethod:TWRequestMethodGET];
        [request setAccount:self.account];    
        [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
            if ([urlResponse statusCode] == 200) {
                NSError *jsonError = nil;
    
                self.timeline = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonError];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                });
            }
        }];
    
    }
    

    Parsing the JSON data inside performRequestWithHandler isn’t a bad idea at all. In fact, I don’t see what should be wrong with doing this. You’re working in a nice asynchronous manner, making use of GCD to get back on the main thread – that’s fine!

    A complete discussion of the source I posted can be found here: http://www.peterfriese.de/the-accounts-and-twitter-framework-on-ios-5/, the source is available on Github: https://github.com/peterfriese/TwitterClient

Originally posted 2013-11-16 20:51:10.