gpt4 book ai didi

ios - 在 KVO 中使用嵌套键路径

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

假设我想观察名为“isEnabled”的属性' 在名为“controller”的属性上。据我所知,我有两种安装此类观察的选择:

1. [self.controller addObserver:self forKeyPath:@"isEnabled" options:0 context:nil];
2. [self addObserver:self forKeyPath:@"controller.isEnabled" options:0 context:nil];

我注意到这两种方法之间的实际区别 - 在第二种方法中,如果 self 上的“ Controller ”对象被替换,我会收到通知,而在第一种方法中,我只会在“isEnabled”时收到通知。 ' 属性在我安装观察的同一个实例上发生了变化。

我的问题是,如果有的话,这到底是在哪里记录的?我知道它有效,但我应该使用它吗?
我在 Apple 文档中找不到任何提及此类行为的信息,尽管其他一些人在论坛中提到了它。我们很乐意接受任何引用。

谢谢。

最佳答案

不仅仅是当 controller 属性改变时你会收到一个改变通知,KVO 会切换到跟踪新 Controller 的 isEnabled 属性并停止跟踪旧 Controller 的 isEnabled 属性。

这隐含在关键路径的概念中。键值观察建立在键值编码之上。 Key-Value Coding Programming Guide 在 Key-Value Coding Fundamentals 中对键路径进行了说明:

A key path is a string of dot separated keys that is used to specify a sequence of object properties to traverse. The property of the first key in the sequence is relative to the receiver, and each subsequent key is evaluated relative to the value of the previous property.

For example, the key path address.street would get the value of the address property from the receiving object, and then determine the street property relative to the address object.

-addObserver:forKeyPath:options:context: 的含义不是“按照关键路径到达最后一个元素并观察倒数第二个对象的该属性”。它是“观察接收者对象的这个关键路径”。关键路径始终被认为是从接收者开始的。

换句话说,对于你的第二个代码示例,它不是“观察 selfcontrollerisEnabled 属性”(那是你的第一个例子的意思)。意思是“观察selfcontroller.isEnabled。任何时候计算表达式[self valueForKeyPath:@"controller.isEnabled"]<的结果 已经或可能已经改变,通知我。”

I know it works but should I use it?

是的,你应该使用它。这是 API 的预期含义。这就是该方法将其参数描述为键路径而不仅仅是键的原因。

关于ios - 在 KVO 中使用嵌套键路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28167684/

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