帮助更改textLabel的NSTimer。代码包括在内

时间:2010-11-10 15:24:01

标签: iphone xcode

想要将我的NSTimer代码更改为使用applicationSignificantTimeChange

这就是我现在所拥有的。

基本上我想更改计时器,而不是每5秒更换一次,例如我希望这些textLabels在每天晚上12点更改,有人帮助我吗?

//h file

NSTimer *timer;

IBOutlet UILabel *textLabel;

//m file

- (void)onTimer {

    static int i = 0;

    if ( i == 0 ) { 
        textLabel.text = @"iphone app";
    }

    else if ( i == 1 ) {
        textLabel.text = @" Great App!";
    }

    else if ( i == 2 ) {
        textLabel.text = @" WOW!";
    }

    else {
        textLabel.text = @" great application again!!";
        i = -1;
    }

    i++;
}


timer =[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES]; 

3 个答案:

答案 0 :(得分:13)

您可以做两件事来响应applicationSignificantTimeChange:

(1)如果你有一个应该更新的视图控制器的连接,只需在app delegate中实现applicationSignificantTimeChange:

- (void)applicationSignificantTimeChange:(UIApplication *)application {
  yourViewController.textLabel.text = @"random text";
}

(2)在应该获得更新的视图控制器中订阅UIApplicationSignificantTimeChangeNotification通知。您也许可以将该代码放在viewDidLoad

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onSignificantTimeChange:)
                                                 name:UIApplicationSignificantTimeChangeNotification 
                                               object:nil];
}

- (void)onSignificantTimeChange:(NSNotification *)notification {
    self.textLabel.text = @"random text";
}

您还需要致电

[[NSNotificationCenter defaultCenter] removeObserver:self];

在不再需要视图控制器的某个地方。

答案 1 :(得分:0)

计时器的选择器应为:

-(void) onTimer:(NSTimer *) timer
{
   // yourcode

}

并致电:

[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];

您需要“onTimer * *”


[编辑]

用于调用将在12:00开始的函数,对于低性能(即不是12:00:00:0000),您可以执行以下操作,就像位于后台的应用程序一样:

NSTimeInterval minute = 60.0f
[NSTimer scheduledTimerWithTimeInterval:minute target:self selector:@selector(onTimer:) userInfo:nil repeats:YES]

-(void) onTimer:(NSTimer *) timer
{
   NSDate *midnight = [NSDate dateWithNaturalLanguageString:@"today at 12:00 am"]; // unsure of this line
   if ([midnight timeIntervalSinceDate:[NSDate date]] < 30.0f)
      // set off alarm.

}

答案 2 :(得分:0)

对我来说似乎很简单 - 只需在午夜创建一个NSDate,计算24小时的时间间隔(以秒为单位),然后创建NSTimer - (id)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats