Iphone: execute Selector: withObject: afterDelay: doesn't work with background thread?

I want to run a method in a background thread, the first method will run another method in the same (background) thread in a few seconds. I wrote this:

- (IBAction)lauch:(id)sender { [self performSelectorInBackground:@selector(first) withObject:nil]; } -(void) second { printf("second\n"); } -(void) first { NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init]; printf("first\n"); [self performSelector:@selector(second) withObject:nil afterDelay:3]; printf("ok\n"); [apool release]; } 

but the second method is never called, why? and how can I achieve my goal?

thanks

+7
objective-c iphone
source share
1 answer

You must have a runSelector: withObject: afterDelay: run loop to work.


Your code executes first , and when first exits, the thread has disappeared. You need to run a run loop.

Add

 [[NSRunLoop currentRunLoop] run]; 

At the end of the first .

+9
source share

All Articles