首页 > 解决方案 > 我应该在视图控制器中编写 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,还是为它们创建一个委托类?或者(在网上闲逛了一下之后),设置一个NSNotificationthat,在 2 分钟后,调用setPumpInfo:select:runPump

无论哪种最佳选择,您能否也解释一下其中的原因。我正在尝试更多地了解设计模式,并知道如何在正确的场景中使用它们。谢谢!

标签: objective-cuiviewcontrollerdelegatesnstimernsnotificationcenter

解决方案


我会有一个NSObject子类来模拟你的泵。我会给这个 asetInfo和 arunstop方法(至少)。

ViewControllers应该控制视图并与模型进行交互,因此他们将创建与之交互的新泵对象(模型)。

现在,您可能想向Pump:添加另一个方法runAfterDelay:(NSTimeInterval)delay forDuration:(NSTimeInterval) duration并将 嵌入到NSTimerPump中。

然后,您可以在视图控制器中使用泵,如下所示:

-(void) startPump {
    [self.pump setInfo:SALINE select:0];
    [self.pump runAfterDelay: 120 forDuration: 120];
}

将逻辑保留在视图控制器之外,因此您不必复制它。


推荐阅读