ios - 在后台更新 NSDate 和 NSString

标签 ios iphone objective-c nsstring

美好的一天!我只想问一下我如何在后台更新这些代码?

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy/MM/dd  hh:mm:ss"];
self.txtTimestamp.text = [formatter stringFromDate:[NSDate date]];

NSString *buyUrl = @"https://docs.google.com/spreadsheet/pub?key=0AkgWFqjLQz0TdHdMQzBsc1lhaGFPZEFCYXBLWEt1Q0E&single=true&gid=3&output=txt";
NSString *buyFile= [NSString stringWithContentsOfURL:[NSURL URLWithString:buyUrl] encoding:NSUTF8StringEncoding error:nil];
self.txtBuydata.text = buyFile;

如果应用程序是新打开的,则日期和时间正在更新,因为它在 ViewDidLoad 和 NSString 代码中。现在,如何每分钟在后台更新 NSDate 和 NSString?所以即使应用程序在后台,NSSting 也会每分钟更新一次,即使应用程序在后台或打开。非常感谢!

最佳答案

您需要使用NSTimer 重复执行一个 Action 。

示例:

- (void)viewDidLoad {
    //...
    //declare "NSTimer *timerTest;" in the .h
    timerTest = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                 target:self
                                               selector:@selector(doThisRepeatedly:)
                                               userInfo:nil
                                                repeats:YES];
    //...
}

- (void)doThisRepeatedly:(NSTimer *)sender
{
    NSLog(@"%@",sender);
    //...
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy/MM/dd  hh:mm:ss"];
    self.txtTimestamp.text = [formatter stringFromDate:[NSDate date]];
    //...

    //fyi: if you want to stop the timer from within this method (generally in a condition)
    //then use the following commented line:
    //[sender invalidate];
}

要从另一个方法中停止计时器,然后通过它的对象名称引用它并简单地:

[timerTest invalidate];

关于ios - 在后台更新 NSDate 和 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21013034/

相关文章:

ios - 图片无法上传到 php 服务器 ios 10

ios - CATextLayer位于CALayer的顶部吗?

iphone - 用于旋转、调整大小、在 UIView 边缘移动的 UIGestureRecognizer

iOS 推送通知自签名证书

objective-c - 在核心数据中保存图像的最佳方式

ios - 从子类设置父类(super class)的属性?

ios - 刷新时表中的 WKinterfaceImage 丢失图像

ios - 当需要一些额外内存时,iOS 是否会释放 UITabBar 选项卡中加载的数据?

iphone - 更改按钮的外观 - iPhone

android - youtube iframe API 中的广告不适用于 ipad、iphone 和 android