gpt4 book ai didi

ios - dispatch_after 与 performSelector afterDelay

转载 作者:可可西里 更新时间:2023-11-01 04:41:55 25 4
gpt4 key购买 nike

我正在编写一个带有 slider 的游戏。为了从解决状态开始随机播放游戏,我想定期重复调用 pushRandomPiece 以直观地随机播放游戏。

我一开始想使用 dispatch_after 但我对触发日期有疑问:

这个有效:

-(void)shuffle {
for (int i=0; i<50;i++)
[self performSelector:@selector(pushRandomPiece) withObject:nil afterDelay:i*0.50*2];
}

pushRandomPiece 中两次连续调用之间的差异几乎始终等于一秒。

但这行不通:

-(void)shuffle {
for (int i=0; i<50;i++)
// [self performSelector:@selector(pushRandomPiece) withObject:nil afterDelay:i*0.50*2];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, i*NSEC_PER_SEC*0.5*2), dispatch_get_main_queue(), ^{ [self pushRandomPiece]; });
}

这是连续调用之间的时间差:

2013-10-01 11:02:53.147 SlidingPuzzle[2006:60b] diff= 1.077376
2013-10-01 11:02:54.262 SlidingPuzzle[2006:60b] diff= 1.111863
2013-10-01 11:02:55.335 SlidingPuzzle[2006:60b] diff= 1.070456
2013-10-01 11:02:56.455 SlidingPuzzle[2006:60b] diff= 1.117381
2013-10-01 11:02:57.542 SlidingPuzzle[2006:60b] diff= 1.084070
2013-10-01 11:02:58.655 SlidingPuzzle[2006:60b] diff= 1.110574
2013-10-01 11:02:59.757 SlidingPuzzle[2006:60b] diff= 1.098654
2013-10-01 11:03:00.862 SlidingPuzzle[2006:60b] diff= 1.103132
2013-10-01 11:03:01.956 SlidingPuzzle[2006:60b] diff= 1.091535
2013-10-01 11:03:03.050 SlidingPuzzle[2006:60b] diff= 1.090532
2013-10-01 11:03:04.160 SlidingPuzzle[2006:60b] diff= 1.107981
2013-10-01 11:03:04.164 SlidingPuzzle[2006:60b] diff= 0.000982
2013-10-01 11:03:06.354 SlidingPuzzle[2006:60b] diff= 2.187945
2013-10-01 11:03:06.357 SlidingPuzzle[2006:60b] diff= 0.000862
2013-10-01 11:03:08.498 SlidingPuzzle[2006:60b] diff= 2.139442
2013-10-01 11:03:08.501 SlidingPuzzle[2006:60b] diff= 0.000805
2013-10-01 11:03:10.750 SlidingPuzzle[2006:60b] diff= 2.246749
2013-10-01 11:03:10.753 SlidingPuzzle[2006:60b] diff= 0.000839

下面是让方 block 移动的方法:

-(void) pushRandomPiece {
NSSet * s = [self freeBlocks];
int n = [s count];
int piece = arc4random_uniform(n);
Piece * p = [[s allObjects] objectAtIndex:piece];
dispatch_async(dispatch_get_main_queue(), ^{
[self pushPiece:p];
});
}

最佳答案

dispatch_after 仅在您指定的时间后将您的 block 添加到队列中。如果队列为空,您的 block 可能会在添加到队列后立即运行。否则,它可能会在运行之前在队列中等待一段时间——等待其他任务完成。

关于ios - dispatch_after 与 performSelector afterDelay,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19112182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com