我有一个 UILabel,它会随机显示我提供的列表中的文本。
我希望 UILabel 每天显示一项。
处理这个问题的最佳方法是什么?
我应该使用 NSTimer 还是有不同的方法?
我不担心一天中的特定时间,只是 UILabel 每天更新一次。
谢谢!
我有一个 UILabel,它会随机显示我提供的列表中的文本。
我希望 UILabel 每天显示一项。
处理这个问题的最佳方法是什么?
我应该使用 NSTimer 还是有不同的方法?
我不担心一天中的特定时间,只是 UILabel 每天更新一次。
谢谢!
一种选择是将当前日期保存到NSUserDefaults
显示标签时。
当你的视图控制器被加载时,你会从NSUserDefaults
. 如果保存日期和“现在”之间的差异超过 24 小时,则更新标签(并保存新日期),否则显示当前标签。
您可能还希望视图控制器侦听“将进入前台”通知。每次您的应用程序返回前台时,您都需要进行相同的检查。
将日期存储在首选项中,并比较应用程序何时进入前台。你的 appDelegate 看起来像这样:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:[NSDate date] forKey:@"savedDate"];
[prefs synchronize];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSDate *savedDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"savedDate"];
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitDay fromDate:savedDate toDate:[NSDate date] options:0];
if ([dateComponents day] >= 1) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"updateLabel" object:nil];
}
}
然后在您的视图控制器中,监听通知:
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLabel) name:@"updateLabel" object:nil];
}
-(void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void) updateLabel {
//update your label here
}
如需在午夜更新,请查看UIApplicationSignificantTimeChangeNotification
. 这里有一个相关的答案:https ://stackoverflow.com/a/15537806/1144632