【问题标题】:Swift: Boolean attributes and KVC mysteriesSwift:布尔属性和 KVC 奥秘
【发布时间】:2016-02-16 17:27:14
【问题描述】:

所以我在玩这个简单的 CoreData 实体

import CoreData

class Figure: NSManagedObject {
    @NSManaged var approx: NSNumber? // Defined as Boolean type without default value
}

如你所料,对于一个新人物,你会得到

figure.approx # nil
figure.valueForKey("approx") # nil

但是,如果您定义以下内容(是的,我知道,我可以在数据模型中设置一个默认值,这不是重点)

var isApprox: Bool {
  guard let approx = approx else { return false }
  return approx == true
}

然后突然

figure.valueForKey("approx") # false

好吧,出于某种(对我而言)神秘的原因,它实际上依赖于 isApprox。我假设它是合成的,我在不知不觉中覆盖了它,但如果你删除 isApprox 声明并尝试使用 KVC 调用它,它会崩溃:

figure.valueForKey("isApprox") # Execution was interrupted

如果您具备以下条件,则更进一步:

class Figure: NSManagedObject {
    @NSManaged var approx: NSNumber?

    var isApproximate: Bool {
      guard let approx = approx else { return false }
      return approx == true
    }
}

现在你得到

figure.valueForKey("approx") # nil - expected
figure.valueForKey("isApproximate") # false - expected
figure.valueForKey("approximate") # false - where does this one come from?
figure.isApprox # error: value of type 'Figure' has no member 'isApprox'

我找不到任何关于此的文档,我很想了解发生了什么。

【问题讨论】:

    标签: swift core-data boolean kvc


    【解决方案1】:

    我认为 Key Value Coding Reference 手册中的 this article 涵盖了您注意到的行为。

    具体来说,标题为“valueForKey: 的默认搜索模式”的部分表明,对于给定的键,valueForKey: 将尝试一系列不同的访问器方法,包括“key”和“isKey”(有趣的是,它会在其中任何一个之前尝试“getKey”)。

    【讨论】:

    • 是的,但 <key><isKey> 之前尝试,因此在这种情况下,应优先使用 approx 托管属性而不是 isApprox 属性。
    • @MartinR 好点。也许那是因为approx 是一个实例变量,只有在没有访问器方法 时才会尝试。但我猜。
    • approx 是 Core Data 属性,访问器方法是在运行时动态创建的。但我仍然想知道它为什么会这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2019-12-06
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多