【问题标题】:Should I write NSTimer code in view controller or separate class with either delegation/notification pattern?我应该在视图控制器中编写 NSTimer 代码还是使用委托/通知模式单独的类?
【发布时间】: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


【解决方案1】:

我会有一个NSObject 子类来为您的泵建模。 我会给这个setInforunstop 方法(至少)。

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

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

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

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

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

【讨论】:

  • 好主意,讽刺的是我已经说过Pump 模型已经到位,但我喜欢你在该模型中添加计时器控件的建议。到目前为止,我在模型中所做的只是创建具有泵的相关属性(速度、方向等)的 Pump 对象。但我一直在通过MotorViewController 操作这些属性。但是我对现在属于哪里的东西有了更好的理解,谢谢 davbryn
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 2012-10-24
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多