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


当前回答

我认为您正在寻找dispatch_after()。它要求你的块不接受参数,但是你可以让块从你的局部作用域捕获这些变量。

int parameter1 = 12;
float parameter2 = 144.1;

// Delay execution of my block for 10 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    NSLog(@"parameter1: %d parameter2: %f", parameter1, parameter2);
});

更多:https://developer.apple.com/documentation/dispatch/1452876-dispatch_after

其他回答

您可以使用dispatch_after稍后调用一个块。在Xcode中,开始输入dispatch_after并按Enter键自动完成如下内容:

下面是一个使用两个浮点数作为“参数”的示例。你不需要依赖任何类型的宏,代码的意图是非常清楚的:

斯威夫特3,斯威夫特4

let time1 = 8.23
let time2 = 3.42

// Delay 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    print("Sum of times: \(time1 + time2)")
}

斯威夫特2

let time1 = 8.23
let time2 = 3.42

// Delay 2 seconds
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
        println("Sum of times: \(time1 + time2)")
}

Objective - C

CGFloat time1 = 3.49;
CGFloat time2 = 8.13;

// Delay 2 seconds
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    CGFloat newTime = time1 + time2;
    NSLog(@"New time: %f", newTime);
});

PerformSelector:WithObject总是接受一个对象,因此为了传递诸如int/double/float等参数.....你可以用这样的东西。

//NSNumber是一个对象

[self performSelector:@selector(setUserAlphaNumber:)
     withObject: [NSNumber numberWithFloat: 1.0f]       
     afterDelay:1.5];



-(void) setUserAlphaNumber: (NSNumber*) number{

     [txtUsername setAlpha: [number floatValue] ];

}

同样的方式,你可以使用[NSNumber numberWithInt:]等....在接收方法中,您可以将数字转换为[数字int]或[数字double]的格式。

Swift 3和Xcode 8.3.2

这段代码将帮助你,我也添加了一个解释

// Create custom class, this will make your life easier
class CustomDelay {

    static let cd = CustomDelay()

    // This is your custom delay function
    func runAfterDelay(_ delay:Double, closure:@escaping ()->()) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}


// here how to use it (Example 1)
class YourViewController: UIViewController {

    // example delay time 2 second
    let delayTime = 2.0

    override func viewDidLoad() {
        super.viewDidLoad()

        CustomDelay.cd.runAfterDelay(delayTime) {
            // This func will run after 2 second
            // Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
            self.runFunc()
        }
    }

    // example function 1
    func runFunc() {
        // do your method 1 here
    }
}

// here how to use it (Example 2)
class YourSecondViewController: UIViewController {

    // let say you want to user run function shoot after 3 second they tap a button

    // Create a button (This is programatically, you can create with storyboard too)
    let shootButton: UIButton = {
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 15, y: 15, width: 40, height: 40) // Customize where do you want to put your button inside your ui
        button.setTitle("Shoot", for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // create an action selector when user tap shoot button
        shootButton.addTarget(self, action: #selector(shoot), for: .touchUpInside)   
    }

    // example shoot function
    func shoot() {
        // example delay time 3 second then shoot
        let delayTime = 3.0

        // delay a shoot after 3 second
        CustomDelay.cd.runAfterDelay(delayTime) {
            // your shoot method here
            // Update your UI here, u don't need to worry to bring this to the main thread because your CustomDelay already make this to main thread automatically :)
        }
    }   
}

于2021年4月更新,使用Xcode 12.4。这仍然有效,除了现在+按钮显示更多的图标,包括视图库和Modifiers库(见下文),并且视图可能是默认的。 所以一定要选择Snippets库,如下图所示。


(2020年6月在Xcode 11.3.1上验证)

Xcode提供了一个代码片段来做到这一点。您只需输入延迟值和希望在延迟后运行的代码。

点击Xcode右上方的+按钮,当你在编辑一些代码时(而不是在Project Navigator中,在那里会显示其他库,如Capabilities) 确保Snippets库(参见截图,带有{}的图标)被选中,从可用的图标中退出。 搜索之后 它将只返回一个搜索结果,这是所需的片段(见截图)。双击它,你就可以开始了。

在swift 3中,我们可以简单地使用DispatchQueue.main.asyncAfter函数在延迟'n'秒后触发任何函数或动作。在代码中,我们将延迟设置为1秒后。在此函数体中调用将在延迟1秒后触发的任何函数。

let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when) {

    // Trigger the function/action after the delay of 1Sec

}