我想我需要一些帮助。

在我的应用程序中,确实有一个UILabel,其文本来自“整数”。每当View加载时,它都会获取NSUserDefaults中实际存储的整数值:

NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.sam.Widget"];
counter = [defaults integerForKey:@"MyNumberKey"];
numberLabel.text = [NSString stringWithFormat:@"%d", counter];


另外,我确实有一个NC-Widget,其执行方式与应用程序本身相同。 “整数”的值通过应用组进行同步,因此当我在Widget中更改整数的值时,它将值存储在NSUserDefaults中。

所以,我的问题是,第二个方向(从小部件到应用程序)仅在应用程序本身关闭时才起作用,甚至没有隐藏。

因此,当我关闭通知中心时,如何在App中更新UILabel,以便它可以识别我对小部件中的整数所做的更改?

如果您能帮助我,我将不胜感激。
-山姆

最佳答案

如果您打开通知中心,则该应用程序将进入后台。因此,当事件重新回到前台时,您需要捕获该事件。您可以由视图控制器中的观察者对系统通知执行此操作。如果您想观察自己的通知,可以在AppDelegate中处理这些通知:
    applicationWillEnterForeground:(UIApplication *)application

不要忘记取消订阅dealloc。 (在ARC中也仍在调用它)

- (void) handleEnterForeground: (NSNotification*) sender{
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.sam.Widget"];
counter = [defaults integerForKey:@"MyNumberKey"];
numberLabel.text = [NSString stringWithFormat:@"%d", counter];
}

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

- (void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self forKeyPath:@"UIApplicationWillEnterForegroundNotification"];
}

关于ios - 关闭通知中心时更新标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28525621/

10-11 22:14
查看更多