【问题标题】:Objective C repeated callback requiredObjective C 需要重复回调
【发布时间】:2014-08-19 14:57:14
【问题描述】:

我是 iOS 开发的新手,我一直在尝试解决以下问题:

我有一个ViewController 显示随时间变化的信息。我有另一个控制器 (TimeController) 管理时间。 TimeController 有一个 NSTimer 每秒触发一次以检查我是否进入了一个新的时间段(这背后有一些逻辑,如果我进入了一个新的时间段,这意味着 ViewController 中的信息需要待更新。

据我了解,我需要某种回调程序,但我不知道该怎么做 - 我阅读了有关块的内容,但老实说,它们非常令人难以抗拒,我无法将我的问题与示例联系起来我看到了。

TimeController 如下所示:

// TimeController.h

@interface TimeController : NSObject

@property (weak) NSTimer *periodicTimer;
@property NSInteger timeslot;

@end

// TimeController.m
#import "TimeController.h"

@implementation TimeController

-(void)startTimer {
    self.periodicTimer = [NSTimer scheduledTimerWithTimeInterval:(1) target:self 
             selector:@selector(onTimer) userInfo:nil repeats:YES];
}

-(void)onTimer {
    // check if anything has changed.
    // If so, change timeslot. Notify "listening" objects.
}

在一个简单的例子中,单个 ViewController 取决于 TimeController,我想象的是这样的:

// ViewController.h
@interface ViewController : UIViewController

@property TimeController* timeCtrl;

@end

// ViewController.m
#import "ViewController.h"
#import "TimeController.h"

-(void)onNotificationFromTimeController {
    // timeslot has changed in the TimeController.
    NSInteger tslot = timeCtrl.timeslot;

    // figure out new display value depending on tslot. Update the view
}

这里缺少的是回调机制(以及正确初始化timeCtrl 等其他内容)。对此我将不胜感激!

【问题讨论】:

    标签: ios objective-c callback objective-c-blocks nsnotificationcenter


    【解决方案1】:

    通知

    ViewController中的事件添加一个监听器(我们称之为“TimeNotificationEvent”):

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onNotificationFromTimeController) name:@"TimeNotificationEvent" object:nil];
    

    TimeController.monTimer方法中,添加如下代码发布通知:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeNotificationEvent" object:nil];
    

    旁注:停止收听通知:

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"TimeNotificationEvent" object:nil];
    
    • 易于设置
    • 同一事件可以有多个侦听器

    TimeController.h中添加属性:

    @property (nonatomic, copy) dispatch_block_t timerBlock;
    

    TimeController.m中添加对timerBlock的调用:

    -(void)onTimer {
        // Check for nil to avoid crash
        if (_timerBlock) {
            _timerBlock();
        }
    }
    

    ViewController中分配块:

    _timeCtrl.timerBlock = ^{
        // Do stuff to the UI here
    };
    
    • 有点复杂(保留循环、语法等)
    • 只有一个侦听器(使用此特定示例实现)
    • 更容易遵循代码

    【讨论】:

    • 哇,这真的很优雅,似乎正是我所希望的!谢谢!
    • 添加了一个使用块的解决方案的快速示例,因为您要求使用块,但我相信通知应该可以正常工作
    • 也感谢 Block 版本!实际上,通知对我来说应该是完美的——我只是不知道它们。我希望多个视图控制器监听同一个计时器。我一直在用错误的关键字搜索:)
    猜你喜欢
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 2012-05-07
    相关资源
    最近更新 更多