gpt4 book ai didi

swift - Swift 中键值编码的使用

转载 作者:搜寻专家 更新时间:2023-11-01 06:55:53 27 4
gpt4 key购买 nike

我想知道 KVO 在 swift 中的使用,正如我在 Apple Doc 或任何其他在线文章中所读到的那样,它指出它提供对属性的间接访问并可通过字符串寻址。我有一系列疑问。

  • 如果我可以直接通过person.name = "John" 设置属性,他们为什么要使用Set Value for key name =间接地“约翰”
  • Apple 文档表示,键值编码兼容可以参与范围广泛的 Cocoa 技术,例如 Core Data。为什么它被使用而不是在其他框架中使用
  • 它在运行时使用或动态设置值。怎么样?
  • 它是 TypeSafe 吗?如何实现?
  • 它是一个 Objective - C 特性,那么为什么仍然在 Swift 4 中使用并通过 ./Type.property 访问和设置进行最新改进

最佳答案

If I can set the property directly via person.name = "John" they why to use a Set Value for key name = "John" indirectly

请阅读“What is the point of key-value coding?”


Apple doc says key-value coding compliant can participate in a wide range of Cocoa technologies like Core Data. Why it's used and not in other frameworks

在适当的地方使用它。它用于有用且性能可接受的地方。如果它没有用,或者如果它的性能太低,它就不会被使用。


It is used during runtime or dynamic to set value. How it is?

键值编码使用 Objective-C 运行时来查找 getter 和 setter 方法,并在 setter 不存在的情况下查找实例变量的类型和位置。参见 Friday Q&A 2013-02-08: Let's Build Key-Value Coding进行详分割析。

Apple 文档简要描述了 Key-Value Observing 的实现 here .它足够短,可以完整引用:

Automatic key-value observing is implemented using a technique called isa-swizzling.

The isa pointer, as the name suggests, points to the object's class which maintains a dispatch table. This dispatch table essentially contains pointers to the methods the class implements, among other data.

When an observer is registered for an attribute of an object the isa pointer of the observed object is modified, pointing to an intermediate class rather than at the true class. As a result the value of the isa pointer does not necessarily reflect the actual class of the instance.

You should never rely on the isa pointer to determine class membership. Instead, you should use the class method to determine the class of an object instance.

Mike Ash 在 Friday Q&A 2009-01-23 中给出了更详细的分析.


Is it TypeSafe and how?

它不是特别安全的类型。例如,它不会阻止您将 UIView 存储在声明为 NSString 的属性中,反之亦然。

Its an Objective - C feature then why still used in Swift 4 with latest improvements with ./Type.property access and set

它仍在使用,因为大多数 Apple 的 SDK 仍然在 Objective-C 中实现,并且因为它可以让你做一些你在 Swift 中做不到的事情,而不需要更多的“样板”(手动,重复的功能)。权衡是 Objective-C 的性能较低。在很多很多情况下,Objective-C 的较低性能(与 Swift 相比)并不是一个严重的问题,增加的活力非常有帮助。

关于swift - Swift 中键值编码的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53407131/

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