【发布时间】:2019-05-07 16:03:00
【问题描述】:
我的MotorViewController 中有 5 个按钮,用作 5 个电机的开/关开关。按下按钮 A,电机 A 将无限期运行,直到您再次按下按钮停止。
我刚刚添加了第 6 个按钮,它将告诉电机 A 运行 2 分钟。我在ViewController 中添加了NSTimer 代码,一切正常。 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,在 2 分钟后调用setPumpInfo:select: 和runPump?
无论哪个是最好的选择,您能否解释一下其中的原因。我正在尝试更多地了解设计模式,并知道如何在正确的场景中使用它们。谢谢!
【问题讨论】:
-
您应该在每个 Viewcontroller 中创建计时器。并在彼此导航时停止计时器。
标签: objective-c uiviewcontroller delegates nstimer nsnotificationcenter