I'm developing a UIView where there must be a process that accesses to remote database and must update a UITableView with the retrieved results.
To do that I'm planning use a NSTimer that runs each 10 seconds the update process where database is accessed and data retrieved.
The problem is that if I run this in the main thread the view will be frozen till the data is retrieved and loaded.
Anyone knows wicht is the best way to do that? Any example will be apreciated.
Thanks.
EDIT ----
This is the code that I'm using to start & stop the update process:
-(void)startUpdating
{
self.isUpdating = YES;
timerLoop = [[NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(listMustBeUpdated:) userInfo:nil repeats:YES] retain];
[[NSRunLoop mainRunLoop] addTimer: timerLoop
forMode: UITrackingRunLoopMode];
}
-(void)stopUpdating
{
self.isUpdating = NO;
[timerLoop invalidate];
[timerLoop release];
timerLoop = nil;
}
In addition, after a few minutes running the app chashes without error message. I think that is because memory usage or zombies, but I've tested with instruments and the memory usage was of 3.11 Mb(live) & no zombies.
Maybe is because the timer?
Thanks.
EDIT --- 2
Ok, now this is the code I'm using for the whole matter, and still freezing the UITableView while scrolls.
Maybe is because is updated from the thread and the scrolling is executed from the main thread?
-(void)loadMessagesFromUser:(int)userId toUserId:(int)userToId
{
fromUserId = userId;
toUserId = userToId;
messages = [OTChatDataManager readMessagesFromUser:userId toUser:userToId];
lastMessageId = [[messages getValueByName:@"Id" posY:[messages CountY]-1] intValue];
[list reloadData];
}
-(void)messagesMustBeUpdated:(id)sender
{
if ([NSThread isMainThread]) {
[self performSelectorInBackground:@selector(updateMessages:) withObject:nil];
return;
}
}
-(void)updateMessages:(id)sender
{
iSQLResult *newMessages = [OTChatDataManager readMessagesFromUser:fromUserId toUser:toUserId sinceLastMessageId:lastMessageId];
for (int a=0;a<[newMessages CountY];a++)
{
[messages.Records addObject:[newMessages.Records objectAtIndex:a]];
messages.CountY++;
}
lastMessageId = [[messages getValueByName:@"Id" posY:[messages CountY]-1] intValue];
[list reloadData];
}
-(void)startUpdating
{
self.isUpdating = YES;
timerLoop = [[NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(messagesMustBeUpdated:) userInfo:nil repeats:YES] retain];
}
-(void)stopUpdating
{
self.isUpdating = NO;
[timerLoop invalidate];
[timerLoop release];
timerLoop = nil;
}
loadMessagesFromUser can be called from the mainThread and accesses the same nonatomic object. Is possible the quiet crash because this?
start and stop functions are called from the main thread. The rest is the timer stuff.
Thanks for the replies.