user5047504
user5047504

Reputation:

performSelector: didn't work properly when using dispatch_async and global_queue

I want to ask is there some underlying reason that performSelector: method need its own runloop timer to work properly, because if i don't set a runloop especially for him , he will quit his job!

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    NSLog(@"touchesBegan --- %@", [NSThread currentThread]);

    dispatch_async((dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)), ^{
        [self performSelector:@selector(test) withObject:nil afterDelay:2.0];

/**
*  uncomment this line to make it work
*/
       // [[NSRunLoop currentRunLoop] run];

    });

}

-(void)test
{
    NSLog(@"test --- %@", [NSThread currentThread]);
}

Upvotes: 2

Views: 62

Answers (1)

V.J.
V.J.

Reputation: 9580

I think you must need to call your selector in dispatch_async( dispatch_get_main_queue(), ^{});. Please see the code below.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

NSLog(@"touchesBegan --- %@", [NSThread currentThread]);

    dispatch_async((dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)), ^{
        dispatch_async( dispatch_get_main_queue(), ^{ //ADDED THIS LINE
            [self performSelector:@selector(test) withObject:nil afterDelay:2.0];
            //[[NSRunLoop currentRunLoop] run];
        });//ADDED THIS LINE
    });
}

Upvotes: 1

Related Questions