I am working on performing some tasks in the background every 60 seconds. The background task is the server requests documents to be downloaded form the website. The main thread/UI seems to be locking when the request is done and I am saving the data to sqlite.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSThread detachNewThreadSelector:@selector(startTheBackgroundSync) toTarget:self withObject:nil];
[pool release];
- (void)startTheBackgroundSync {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// [self performSelectorInBackground:@selector(moveSynctoBack) withObject:nil];
// [self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO];
serverSync = [[[ServerSync alloc]init]autorelease];
while (1==1) {
serverSync.delegate = self;
[serverSync syncNow:nil];
[NSThre开发者_JAVA技巧ad sleepForTimeInterval:120];
}
[pool release];
[serverSync release];
}
While the looping does not lock up the main thread, but when ASIHTtpRequest finished with the data it locks up the ui for a second.
The finished selector of an ASIHTTPRequest
will always be performed on the main thread. Therefore you shouldn't do long running tasks there.
Instead of launching a new thread you can schedule a repeated NSTimer:
NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:120 target:self selector:@selector(backgroundSync) userInfo:nil repeats:YES];
... with the following action method:
-(void) backgroundSync
{
ServerSync* serverSync = [[[ServerSync alloc]init]autorelease];
serverSync.delegate = self;
[serverSync syncNow:nil];
}
Be sure that you use the startAsynchronous
-method in ServerSync
to start the request!
Furthermore I'd recommend to implement a singleton and then use it like that:
-(void)init {
[[ServerSync sharedSync] setDelegate:self];
}
-(void) backgroundSync
{
[[ServerSync sharedSync] syncNow];
}
精彩评论