views:

154

answers:

2

I've started a new thread like this:

[NSThread detachNewThreadSelector:@selector(doStuffInThread) toTarget:self withObject:nil];

The thread starts in this method, which performs some delayed stuff:

- (void)doStuffInThread {
    [self performSelector:@selector(delayedMethod) withObject:nil afterDelay:2.0];
}

And then, I check in console if something happened. But nothing happens:

- (void)delayedMethod {
    NSLog(@"it happened!");
}

I don't get an error. But the console stays empty. Is there something wrong with my threading code?

+2  A: 

Here is an example from one of my programs.

- (void)viewDidLoad {
    [super viewDidLoad];
    [NSThread detachNewThreadSelector:@selector(loopSongs) toTarget:self withObject:nil];
}

- (void) loopSongs {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    //do your stuff here 

    [pool release];
}


You don't need the colon after @selector(delayedMethod:) because you don't have any parameters in your method that you are calling.

Garrett
Thanks for pointing this out! It was a typo here at SO. Unfortunately, it wasn't in my real code so the problem is somewhere else...
HelloMoon
Usually when you run a new thread you need to create a `NSAutoreleasePool`, read the following link http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html#//apple_ref/occ/clm/NSThread/detachNewThreadSelector:toTarget:withObject:
Garrett
Read the documentation on this method `+ detachNewThreadSelector:toTarget:withObject:` (SO escaped the last : in the url)
Garrett
+1  A: 

Your background thread's run loop may be terminating before your delayed selector has a chance to execute. Because you won't be blocking the UI on the main thread, you could forgo the delayed selector and instead do something like this:

- (void)doStuffInThread {
    [NSThread sleepForTimeInterval:2.0];
    // Delayed action
}
Brad Larson