ios - 实现这个的好方法?

标签 ios objective-c

这是我的需求:

我正在制作一个控制设备的 iOS 应用程序。它有一个 API,可以让我执行以下操作:

turnOnLights()
turnOffLights()
rotate(degrees)
move(speed)

等等...(API完全是客观的C语言,我只是在C Syntax中给出了一个例子)

通过这个 API,我需要构建高级序列,例如:

   turn on all lights
    wait 1 second
    turn off all lights
   wait 1 second

或者

move
rotate 30 degrees
wait 1 second
move
rotate -30 degrees

我能想到用计时器来做这些事情的 hacky 方法,但我想知道 ObjectiveC 是否有一个很好的方法让我可以构建一些高级方法,例如我可以:

ReturnValue flashLights()
ReturnValue moveAndRotate()

这背后的想法是,执行闪烁操作所需的命令将永远重复发送,而且,我可以这样做:

stopAction(returnValue)

阻止它。 (我知道我正在用 C Syntax 编写,但我发现它可以更清楚地解释事情)。

所以本质上,有没有一种方便的方法来制作类似脚本的东西,我可以在其中调用启动操作的方法。该操作进行方法调用,等待一段时间,执行更多方法调用,并永远重复此操作,直到操作停止。

谢谢

最佳答案

我不确定我是否正确理解了你的问题,但是如果你想重复调用一组中间有延迟的方法,你可以使用performSelector:withObject:afterDelay,或者dispatch_after 构建一个循环。 (而且有很多方法可以离开循环)

[self performSelector:@selector(resetIsBad) withObject:nil afterDelay:0.1];

int delayInSecond = 10;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayInSecond * NSEC_PER_SEC), 
dispatch_get_main_queue(), ^{
   //doing something    
});

performSelector:withObject:afterDelay在延迟后使用默认模式在当前线程上调用接收器的方法。

This method sets up a timer to perform the aSelector message on the current thread’s run loop. The timer is configured to run in the default mode (NSDefaultRunLoopMode). When the timer fires, the thread attempts to dequeue the message from the run loop and perform the selector. It succeeds if the run loop is running and in the default mode; otherwise, the timer waits until the run loop is in the default mode.

dispatch_after 将您的 block 添加到队列中,如果队列为空,它会在添加到队列后立即运行。否则它将不得不等待队列中的其他任务完成才能运行。

更多关于 dispatch_after :

dispatch_after

Enqueue a block for execution at the specified time.

void dispatch_after( dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block);

Parameters:

when The temporal milestone returned by dispatch_time or dispatch_walltime.

queue The queue on which to submit the block. The queue is retained by the system until the block has run to completion. This parameter cannot be NULL.

block The block to submit. This function performs a Block_copy and Block_release on behalf of the caller. This parameter cannot be NULL.

Discussion

This function waits until the specified time and then asynchronously adds block to the specified queue.

Passing DISPATCH_TIME_NOW as the when parameter is supported, but is not as optimal as calling dispatch_async instead. Passing DISPATCH_TIME_FOREVER is undefined.

Declared In dispatch/queue.h

关于ios - 实现这个的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22029472/

相关文章:

ios - 处理滑动删除 Firebase 数据

ios - iPad - 夏令时转换

iOS - 在后台 iOS 8 和 Swift 中播放歌曲 15 分钟后

objective-c - 如何在NSString中使用文本和变量的组合?

objective-c - 是否可以以编程方式生成触摸板手势事件?

ios设置cornerRadius与尾随空格,圆角半径不起作用

objective-c - 帮助正确计算atan2

iphone - 是否需要保存对单例 objective-c 对象的引用,以便在 IOS 应用程序的整个生命周期中保存它?

ios - 如何在我的 iOS 应用程序中获得透明背景,以便我可以看到主屏幕壁纸?

ios - 当我滚动 tableview 时,UITableViewCell 会更改数据和设计