gpt4 book ai didi

ios - 关闭通知中心时更新标签

转载 作者:行者123 更新时间:2023-11-29 02:17:59 25 4
gpt4 key购买 nike

我想我需要一些帮助。

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

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

此外,我还有一个 NC-Widget,它的运行方式与应用程序本身的运行方式相同。 “整数”的值通过应用程序组同步,因此当我更改小部件中的整数值时,它会将值存储在 NSUserDefaults 中。

所以,我的问题是,第二个方向(从 Widget 到 App)仅在 App 本身关闭时才有效,甚至没有隐藏。

那么,当我关闭通知中心时,如何更新应用程序中的 UILabel,以便它识别我对小部件内的整数所做的更改?

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

最佳答案

如果您打开通知中心,应用程序将进入后台。因此,您需要在事件返回前台时捕获该事件。您可以通过 View Controller 中的观察者对系统通知执行此操作。如果您想观察自己的通知,您可以在 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/

25 4 0