是否有一种方法可以在延迟后用一个基本参数调用块,就像使用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
也许比通过GCD更简单,在某个班级(例如。"Util"),或对象上的类别:
+ (void)runBlock:(void (^)())block
{
block();
}
+ (void)runAfterDelay:(CGFloat)delay block:(void (^)())block
{
void (^block_)() = [[block copy] autorelease];
[self performSelector:@selector(runBlock:) withObject:block_ afterDelay:delay];
}
所以要使用:
[Util runAfterDelay:2 block:^{
NSLog(@"two seconds later!");
}];
您可以使用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);
});
根据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];
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]的格式。
这里是我的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内置代码片段库?
Swift更新:
许多向上的投票激励我更新这个答案。
内置的Xcode代码片段库只针对objective-c语言有dispatch_after。人们也可以为Swift创建自己的自定义代码片段。
用Xcode写。
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(<#delayInSeconds#> * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
<#code to be executed after a specified delay#>
})
拖动此代码并将其放入代码片段库区域。
在代码段列表的底部,将有一个名为My code snippet的新实体。编辑这个标题。在输入Xcode时,请填写完成快捷方式。
有关更多信息,请参阅creatingcustomcodesnippet。
更新Swift 3
拖动此代码并将其放入代码片段库区域。
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(<#delayInSeconds#>)) {
<#code to be executed after a specified delay#>
}
对于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)
以下是在Swift中延迟后触发阻塞的方法:
runThisAfterDelay(seconds: 2) { () -> () in
print("Prints this 2 seconds later in main queue")
}
/// EZSwiftExtensions
func runThisAfterDelay(seconds seconds: Double, after: () -> ()) {
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), after)
}
它包括作为一个标准函数在我的回购。
dispatch_after函数在给定时间后将块对象分派到分派队列。使用下面的代码在2.0秒后执行一些UI相关的任务。
let delay = 2.0
let delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
let mainQueue = dispatch_get_main_queue()
dispatch_after(delayInNanoSeconds, mainQueue, {
print("Some UI related task after delay")
})
在swift 3.0中:
let dispatchTime: DispatchTime = DispatchTime.now() + Double(Int64(2.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: {
})
这里有一个方便的帮手来防止烦人的GCD调用一遍又一遍:
public func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void) {
let dispatchTime = DispatchTime.now() + seconds
dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure)
}
public enum DispatchLevel {
case main, userInteractive, userInitiated, utility, background
var dispatchQueue: DispatchQueue {
switch self {
case .main: return DispatchQueue.main
case .userInteractive: return DispatchQueue.global(qos: .userInteractive)
case .userInitiated: return DispatchQueue.global(qos: .userInitiated)
case .utility: return DispatchQueue.global(qos: .utility)
case .background: return DispatchQueue.global(qos: .background)
}
}
}
现在你只需在主线程上延迟你的代码,就像这样:
delay(bySeconds: 1.5) {
// delayed code
}
如果你想延迟你的代码到不同的线程:
delay(bySeconds: 1.5, dispatchLevel: .background) {
// delayed code that will run on background thread
}
如果你喜欢一个框架,也有一些更方便的功能,然后签出handysswift。你可以通过Carthage将它添加到你的项目中,然后像上面的例子一样使用它:
import HandySwift
delay(bySeconds: 1.5) {
// delayed code
}
下面是Swift 3在延迟后排队工作的方法。
DispatchQueue.main.asyncAfter(
DispatchTime.now() + DispatchTimeInterval.seconds(2)) {
// do work
}
我相信作者不是在问如何等待一个分数时间(延迟),而是如何传递一个标量作为参数的选择器(withObject:)和现代objective C中最快的方法是:
[obj performSelector:... withObject:@(0.123123123) afterDelay:10]
你的选择器必须改变它的参数为NSNumber,并使用floatValue或doubleValue这样的选择器检索值
在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
}
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 :)
}
}
}
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
});
于2021年4月更新,使用Xcode 12.4。这仍然有效,除了现在+按钮显示更多的图标,包括视图库和Modifiers库(见下文),并且视图可能是默认的。 所以一定要选择Snippets库,如下图所示。
(2020年6月在Xcode 11.3.1上验证)
Xcode提供了一个代码片段来做到这一点。您只需输入延迟值和希望在延迟后运行的代码。
点击Xcode右上方的+按钮,当你在编辑一些代码时(而不是在Project Navigator中,在那里会显示其他库,如Capabilities) 确保Snippets库(参见截图,带有{}的图标)被选中,从可用的图标中退出。 搜索之后 它将只返回一个搜索结果,这是所需的片段(见截图)。双击它,你就可以开始了。
推荐文章
- 如何停止不必要的UIButton动画标题变化?
- 是否有可能更新一个本地化的故事板的字符串?
- 以编程方式获取Bundle Identifier
- 为iPad和iPhone设计输入按钮
- 如何在我的iPhone应用程序中使用NSError ?
- 我的预发行应用已经在iTunes Connect中“处理”了一周多,这是怎么回事?
- Xcode iOS项目只显示“我的Mac 64位”,但不显示模拟器或设备
- Objective-C中的自动引用计数不能防止或减少什么样的泄漏?
- 在Xcode 9中如何从打开的多个模拟器中退出或关闭单个模拟器?
- 如何使用Swift播放声音?
- UINavigationBar自定义返回按钮没有标题
- 如何精确地以毫秒为单位记录方法的执行时间?
- 在整个UIWindow中获取UIView的位置
- 如何解散ViewController在Swift?
- 保存字符串到NSUserDefaults?