Question

I am writing a Foundation Tool. I have to do the threading to separate to different ongoing tasks.

I tried to do threading but it was continuously getting crashed. And finally I figured out the reason that, I need to have my own runloop running.

Can some one help with with some simple example? I tried following code but it does not work. Every time I run it i crashes with Exception? How can I run a thread in Foundation tool?

@interface MyClass : NSObject
{
}
-(void) doSomething;
@end

@implementation MyClass
-(void) RunProcess:
{
    printf("test");  
}
-(void) doSomething:
{
    [NSThread detachNewThreadSelector: @selector(RunProcess:) toTarget:self withObject: nil];  
}
@end

int main(void)
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    MyClass *myObj = [[MyClass alloc] init],
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 myObj selector:@selector(doSomething:) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];

    [pool drain];
    return 0;
}
Was it helpful?

Solution

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 myObj 
        selector:@selector(doSomething:) userInfo:nil repeats:NO];

Notice your selector is -doSomething: with a colon and argument, yet your method as implemented is -doSomething, without a colon and argument. Actually, your declaration of the method (-doSomething) doesn't match the implementation (-doSomething:). It's not clear if that's just a mistake here in typing your example, or whether that's actually in your code. What is the exception that's raised?

If this mistake is in your code, then the timer ends up trying to send a message to your MyClass object that it won't understand, which raises an exception, most likely.

You should likely change the method your timer is set to fire to the following, as recommended in the documentation for +scheduledTimerWithTimeInterval:target:selector:userInfo:repeats::

@interface MyClass : NSObject {

}
-(void)doSomething:(NSTimer *)timer;
@end

@implementation MyClass

-(void)doSomething:(NSTimer *)timer {
      [NSThread detachNewThreadSelector:@selector(RunProcess:)
       toTarget:self withObject:nil];  
}

@end

OTHER TIPS

Without seeing the exception, allow me to point out that you are trying to schedule a timer on a run loop, using scheduledTimerWithTimeInterval:..., without there being a run loop in place. You should create the timer using timerWithTimeInterval:...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top