【发布时间】: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