是否有一种方法可以在延迟后用一个基本参数调用块,就像使用performSelector:withObject:afterDelay:但是使用int/double/float这样的参数?


当前回答

根据Jaime Cham的回答,我创建了一个NSObject+Blocks类别,如下所示。我觉得这些方法更好地匹配现有的performSelector: NSObject方法

NSObject + Blocks.h

#import <Foundation/Foundation.h>

@interface NSObject (Blocks)

- (void)performBlock:(void (^)())block afterDelay:(NSTimeInterval)delay;

@end

NSObject + Blocks.m

#import "NSObject+Blocks.h"

@implementation NSObject (Blocks)

- (void)performBlock:(void (^)())block
{
    block();
}

- (void)performBlock:(void (^)())block afterDelay:(NSTimeInterval)delay
{
    void (^block_)() = [block copy]; // autorelease this if you're not using ARC
    [self performSelector:@selector(performBlock:) withObject:block_ afterDelay:delay];
}

@end

并像这样使用:

[anyObject performBlock:^{
    [anotherObject doYourThings:stuff];
} afterDelay:0.15];

其他回答

您可以将参数包装在自己的类中,也可以将方法调用包装在不需要在基本类型中传递的方法中。然后在延迟之后调用该方法,并在该方法中执行您希望执行的选择器。

按Cmd + Shift + L显示Xcode内置代码片段库:

寻找分派之后,然后,只需拖放到您的代码。

这里是我的2美分= 5个方法;)

我喜欢封装这些细节,让AppCode告诉我如何完成我的句子。

void dispatch_after_delay(float delayInSeconds, dispatch_queue_t queue, dispatch_block_t block) {
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, queue, block);
}

void dispatch_after_delay_on_main_queue(float delayInSeconds, dispatch_block_t block) {
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_after_delay(delayInSeconds, queue, block);
}

void dispatch_async_on_high_priority_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), block);
}

void dispatch_async_on_background_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block);
}

void dispatch_async_on_main_queue(dispatch_block_t block) {
    dispatch_async(dispatch_get_main_queue(), block);
}

Xcode 10.2和Swift 5及以上

DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
   // code to execute                 
})

ObjC版本

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    //code to execute
});

对于Swift,我已经创建了一个全局函数,没什么特别的,使用dispatch_after方法。我更喜欢这个,因为它易于阅读和使用:

func performBlock(block:() -> Void, afterDelay delay:NSTimeInterval){
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), block)
}

你可以这样使用:

performBlock({ () -> Void in
    // Perform actions
}, afterDelay: 0.3)