延迟后执行方法,不使用NSThread或sleep()——还有其他选项吗?

时间:2022-04-12 04:59:55

Is there a way in iOS4 to call a method after a delay using something else other than NSThread or blocking the UI using sleep()?

iOS4中是否有一种方法可以在使用非NSThread的其他东西延迟之后调用方法,或者使用sleep()阻塞UI ?

6 个解决方案

#1


29  

    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        // code to be executed on main thread.If you want to run in another thread, create other queue
    });

#2


9  

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay

Of NSObject will do this for you.

NSObject会为你做这个。

Additionally, you can create an NSTimer and have it perform a callback to some target and selector after a given amount of time.

此外,您可以创建一个NSTimer,并让它在给定时间后对某些目标和选择器执行回调。

#3


3  

You can using NSTimer. (for example timerWithTimeInterval:target:selector:userInfo:repeats)

你可以使用NSTimer。(例如timerWithTimeInterval:目标:选择器:用户信息:重复)

#4


3  

[self performSelector:@selector(methodName) withObject:nil afterDelay:2.0];

#5


1  

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self 
         selector:@selector(aMethod:) userInfo:nil repeats:NO];

- (void) aMethod:(NSTimer *) aTimer {
  //task to do after the delay.
}

#6


0  

You can easily do that with:

你可以很容易地做到:

[self performSelector:@selector(methodName) withObject:nil afterDelay:5];

#1


29  

    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        // code to be executed on main thread.If you want to run in another thread, create other queue
    });

#2


9  

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay

Of NSObject will do this for you.

NSObject会为你做这个。

Additionally, you can create an NSTimer and have it perform a callback to some target and selector after a given amount of time.

此外,您可以创建一个NSTimer,并让它在给定时间后对某些目标和选择器执行回调。

#3


3  

You can using NSTimer. (for example timerWithTimeInterval:target:selector:userInfo:repeats)

你可以使用NSTimer。(例如timerWithTimeInterval:目标:选择器:用户信息:重复)

#4


3  

[self performSelector:@selector(methodName) withObject:nil afterDelay:2.0];

#5


1  

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self 
         selector:@selector(aMethod:) userInfo:nil repeats:NO];

- (void) aMethod:(NSTimer *) aTimer {
  //task to do after the delay.
}

#6


0  

You can easily do that with:

你可以很容易地做到:

[self performSelector:@selector(methodName) withObject:nil afterDelay:5];