I just ran into a weird behaviour with NSOperation that I fixed but do not understand.
I subclassed NSOperation by following the documentation. When I use the main method below, the application will use 100% or more of the CPU time.
-(void)main
{
@try
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
//Cycle forever until told to cancel
while (![self isCancelled])
{
}
[pool release];
}
@catch(...)
{
// Do not rethrow exceptions.
}
//Finish executing
[self completeOperation]; //Send notificatios using KVO
}
Conversely when I use the following main method, the application uses 3% of the CPU time.
-(void)main
{
@try
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
//Create the initial delayed timers
NSTimer *startUpTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:startUpTimer forMode:NSRunLoopCommonModes];
[runLoop run];
//Cycle forever until told to cancel
while (![self isCancelled])
{
}
[pool release];
}
@catch(...)
{
// Do not rethrow exceptions.
}
//Finish executing
[self completeOperation]; //Send notificatios using KVO
}
This strange behaviour appears to be attributed to the timer. If the timer is asked to not repeat itself, the application uses 100% CPU time, but if the timer is asked to repeat itself, then the CPU usage is normal.
It appears that when nothing is running on the thread, the CPU usage is really high (I would assume it would be the opposite). Any suggestions on why this is the case?
Thanks.