gpt4 book ai didi

ios - 键值观察的新手;为什么我无法在我的 AppDelegate 中监控 int 的值?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:16:52 25 4
gpt4 key购买 nike

我的 Objective-C++ AppDelegate 中有一个名为 stepsCompleted 的公共(public)变量,所以我在 TableView Controller 中使用 [AppDelegate instance]->stepsCompleted 访问它。

我希望我的 TableView Controller 在该变量的值发生变化时告诉我,所以我在我知道正在调用的 initWithCoder: 方法中执行以下操作:

[self addObserver:self forKeyPath:@"[AppDelegate instance]->stepsCompleted" options:0 context:NULL];

然而,尽管我在 AppDelegate 中不断更改 stepsCompleted,但我的方法:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

}

从未被调用。

我究竟做错了什么?

最佳答案

您的代码存在不同的问题。首先,Key-Value Observing 是一种观察对象属性的机制。它不适用于实例变量。因此,您应该将“stepsCompleted”声明为应用程序委托(delegate)的属性而不是实例变量:

@property (nonatomic) int stepsCompleted;

并通过属性访问器方法设置它的值,例如

[AppDelegate instance].stepsCompleted = newValue;

接下来,[AppDelegate instance]->c" 不是关键路径,您必须指定至少一个观察选项,例如NSKeyValueObservingOptionNew

要观察[AppDelegate instance]的“stepsCompleted”属性,应该是

[[AppDelegate instance] addObserver:self 
forKeyPath:@"stepsCompleted"
options:NSKeyValueObservingOptionNew
context:NULL];

关于ios - 键值观察的新手;为什么我无法在我的 AppDelegate 中监控 int 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21443189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com