简体   繁体   English

如何在延迟和后台线程中调用方法

[英]How to call method with delay and in background thread

I have a method what I want to call after -viewDidLoad and in background thread. 我有一个方法,我想在-viewDidLoad和后台线程后调用。 Is there way to combine this two methods: 有没有办法结合这两种方法:

[self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]

and

[self performSelectorInBackground:(SEL) withObject:(id)] ? [self performSelectorInBackground:(SEL) withObject:(id)]

Grand Central Dispatch has dispatch_after() which will execute a block after a specified time on a specified queue. Grand Central Dispatch有dispatch_after() ,它将在指定队列上的指定时间后执行一个块。 If you create a background queue, you will have the functionality you desire. 如果您创建后台队列,您将拥有所需的功能。

dispatch_queue_t myBackgroundQ = dispatch_queue_create("com.romanHouse.backgroundDelay", NULL);
// Could also get a global queue; in this case, don't release it below.
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC);
dispatch_after(delay, myBackgroundQ, ^(void){
    [self delayedMethodWithObject:someObject];
});
dispatch_release(myBackgroundQ);

Try the following: 请尝试以下方法:

// Run in the background, on the default priority queue
dispatch_async( dispatch_get_global_queue(0, 0), ^{
    [self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]
});

Code not tested 代码未经测试

Be aware that your selector/method must not use UIKit (so don't update the UI) or access UIKit properties (like frame) so your selector may need to kick off work back to the main thread. 请注意,您的选择器/方法不能使用UIKit(因此不要更新UI)或访问UIKit属性(如框架),因此您的选择器可能需要将工作重新启动回主线程。 eg 例如

(id)SomeMethod:UsingParams: {

    // Do some work but the results

    // Run in the background, on the main queue
    dispatch_async(dispatch_get_main_queue(), ^{
        // Do something UIKit related
    });
}
[self performSelector:(SEL) withObject:(id) afterDelay:(NSTimeInterval)]

Performs a selector on the thread that it is being called. 在正在调用它的线程上执行选择器。 So when you call it from a background thread it will run there... 所以当你从后台线程调用它时它会在那里运行...

You can do that per example: 您可以按照示例执行此操作:

dispatch_time_t delay = dispatch_time( DISPATCH_TIME_NOW, <delay in seconds> * NSEC_PER_SEC );
dispatch_after( delay, dispatch_get_main_queue(), ^{
    [self performSelectorInBackground: <sel> withObject: <obj>]
});

Somehow a mixed solution. 不知何故,混合解决方案。 It would be better to stick with a full GCD approach tho. 坚持完整的GCD方法会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM