PDA

View Full Version : NSOperationQueue - NSDispatchQueue as replacement of NSThread to do repetitive task




Monaj
Jan 5, 2012, 09:32 AM
Hi All,

I have an application in which I am repetitively calling a method in background. I implemented this by following below steps:

1. created a background thread,
2. called the appropriate method on the created thread,
3. called sleep method on the thread, and
4. again called the previously invoked method.

Below is the code which I used:

- (void) applicationDidFinishLaunching:(NSNotification *)notification
[NSApplication detachDrawingThread:@selector(refreshUserIdPassword) toTarget:self withObject:nil];
}

-(void)refreshUserIdPassword
{
[self getAllUserIdsPasswordsContinousely];
[NSThread sleepForTimeInterval:180];
[self refreshUserIdPassword];

}

I have read that NSThread is not the best way to perform background task, and there are other classes provided in cocoa, such as - NSOperationQueue and NSDispatchQueue, which should be preferred over NSThread to perform an asynchronous task. So I am trying to implement the above specified functionality using the alternative classes.

Problem is - though I am able to perform an asynchronous task using these classes, I am unable to perform a repetitive task (as in my case) using these classes.

Can someone throw some light on this and guide me towards the correct direction?

Thanks,



gnasher729
Jan 5, 2012, 09:47 AM
Go to developer.apple.com, and read up on "blocks" and Grand Central Dispatch. Much more powerful, efficient, and easier to program. You'll need to spend a week learning it all, but that week will be repaid in no time.

Sydde
Jan 5, 2012, 11:35 AM
The key word is "preferred". NSThread is not deprecated, GCD just offers the promise of more efficient use of multi-core processors without any effort on the part of the programmer. Apple themselves say there are still time when using a thread is the better approach.

If I were using blocks to do this, I would consider attaching a NSTimer to the main runloop and using that to toss blocks into the queue.