I have an iPhone
application which in which I want to perform a method in the background every 1
second.
So in my main thread, I have the following code upon my UIViewController
viewDidLoad()
:
[NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(repeatedMethod) userInfo:nil repeats:YES];
with the following methods:
-(void)repeatedMethod {
if(!processIsRunning) {
processIsRunning = YES;
[self performSelectorInBackground:@selector(runProcessInBackground:) withObject:myImage];
}
}
-(void)runProcessInBackground:(UIImage *)image {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
... Some operations ...
... also call a method on the main thread which sets isProcessRunning to NO
[pool release]
}
The way I have this set up, a new thread is spawned every second (unless the process is still running, thanks to my processIsRunning
flag).
Now, my questions are:
(1) Is this the best way to do this? Or is there a more appropriate way to retain and reuse the background thread?
(2) What might be the fastest way to do this? Am I losing time by spinning up new background threads each time the method is called?
The code works fine as is, it's just a quite a bit slower when I ran everything on the main thread (which I ultimately don't want to do).
Any advice would be great! Has anyone dealt with this type of question before?
Many thanks, Brett