I have a UITableView that gets JSON data from a Twitter search. I’m using polling to auto-refresh the view.
In my viewDidLoad, I have:
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(autoTweets:) userInfo:nil repeats:YES];
and then I have:
-(void) autoTweets : (NSTimer *)theTweets
{
NSURL *url = [NSURL URLWithString:@"http://search.twitter.com/search.json?q=%23hatlive%20-%22RT%20%40%22"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection)
{
webData = [[NSMutableData alloc] init];
}
[[self myTableView]setDelegate:self];
[[self myTableView]setDataSource:self];
array = [[NSMutableArray alloc] init];
}
Doing this refreshes the data every 10 seconds. The problem is, if I scroll on the 10th second when the code is executed, the app just crashes. If I don’t scroll, it updates just fine. Does anyone know why?
Assuming
arrayis the data used by the table view’s data source, then the problem is that you change the contents of the array at the start of the connection. Then the contents get updated as the connection completes in the background. Meanwhile, as the table is scrolling, it is still trying to access the old contents of the array.One solution is to setup a temporary array used to deal with the new connection. Don’t update the old array with the new array until just before you call
reloadDataon the table.