objective-c - 我应该在视图控制器中编写 NSTimer 代码还是使用委托/通知模式编写单独的类?
问题描述
我有 5 个按钮MotorViewController
,用作 5 个电机的开/关开关。按下按钮 A,电机 A 将无限期运行,直到您再次按下按钮停止。
我刚刚添加了第 6 个按钮,它将告诉电机 A 运行 2 分钟。我已经NSTimer
在我的代码中添加了代码ViewController
,一切正常。2 分钟后,我调用我的方法,runPump
然后电机自动关闭。
我一直在MotorViewController
大力优化我的,这将是第一次为NSTimer
.
这是代码:
#import "MotorViewController.h"
@interface MotorViewController()
@property (nonatomic, strong) NSTimer *counterTimer;
@end
@implementation MotorViewController
{
int _count;
}
- (void)viewDidLoad
{
_count = 0;
}
// called from the 6th button action method (code is implied)
- (void)setupTimerForCalib
{
self.counterTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timerCount)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.counterTimer forMode:NSRunLoopCommonModes];
NSLog(@"timer started");
}
- (void)timerCount {
_count++;
NSLog(@"count: %d", _count);
if (_count == 120) {
_count = 0;
[self.counterTimer invalidate];
NSLog(@"timer ended");
// timer has ended, shut pump A (SALINE) off
[self setPumpInfo:SALINE select:0];
[self runPump];
}
}
我有另一个视图控制器,我想使用这些方法,所以有更好的理由不只是将它们保留在MotorViewController
.
我应该将这些NSTimer
方法保留在 内MotorViewController
,还是为它们创建一个委托类?或者(在网上闲逛了一下之后),设置一个NSNotification
that,在 2 分钟后,调用setPumpInfo:select:
和runPump
?
无论哪种最佳选择,您能否也解释一下其中的原因。我正在尝试更多地了解设计模式,并知道如何在正确的场景中使用它们。谢谢!
解决方案
我会有一个NSObject
子类来模拟你的泵。我会给这个 asetInfo
和 arun
和stop
方法(至少)。
您ViewControllers
应该控制视图并与模型进行交互,因此他们将创建与之交互的新泵对象(模型)。
现在,您可能想向Pump
:添加另一个方法runAfterDelay:(NSTimeInterval)delay forDuration:(NSTimeInterval) duration
并将 嵌入到NSTimer
类Pump
中。
然后,您可以在视图控制器中使用泵,如下所示:
-(void) startPump {
[self.pump setInfo:SALINE select:0];
[self.pump runAfterDelay: 120 forDuration: 120];
}
将逻辑保留在视图控制器之外,因此您不必复制它。
推荐阅读
- reactjs - 在多层圆环图中输入文本
- python - pyminifier对文件进行压缩后如何运行python
- javascript - Dash python:超过最大更新深度
- rpm - 公开构建需要 golang 1.16+ 的 rpm
- python - 使用 Keras 注意力在 sequence2sequence 模型中连接层形状误差
- python - 在 Windows 10 上安装 PyQt5
- c# - 如何在 Docker 映像中动态设置入口点 dll
- python - 在可执行文件python中包含一个excel文件
- asp.net - 如何在 ASP.NET 身份框架中跳过角色的登录页面
- r - 如何让 gCentroid 在极点工作?