简体   繁体   English

如何设置NSManaged变量?

[英]How to set a NSManaged variable?

I have a NSManagedObject class with two relationships: courseA and courseB . 我有一个具有两个关系的NSManagedObject类: courseAcourseB These relationships should be represented in a dynamic variable. 这些关系应以动态变量表示。 How is it possible to change this variable from outside the class? 如何从类外部更改此变量?

@objc(Universtity)
    public class Universtity: NSManagedObject {

        dynamic var name: String {
            get {
                let name = self.courseA?.name
                return name!
            }
        }
    }

For example from within a ViewController like University.name = University.courseB.name ? 例如从像University.name = University.courseB.name这样的ViewController内部? I was thinking about a Notifikation, but this seems maybe a little more complicated as it could be. 我当时在考虑一个通知,但这似乎可能会有些复杂。

And if there is no other way, how should I implement the observer inside the University class? 如果没有其他方法,我应该如何在大学班级内部实现观察者?

Thank you for every idea. 谢谢你的每一个想法。

Looking at your code, you have declared a "computed" or "ready-only" variable. 查看您的代码,您已声明“计算”或“只读”变量。 This is a variable whose value comes from another variable or combination of variables. 这是一个变量,其值来自另一个变量或变量组合。

I can't see your data model, so it's not clear if you have defined a name parameter in the Core Data model. 我看不到您的数据模型,因此尚不清楚您是否在Core Data模型中定义了名称参数。 Regardless, if you have the logic is somewhat confused, because the getter you have defined means any value it may hold would be ignored anyway. 无论如何,如果您的逻辑有些混乱,因为定义的getter意味着它可能持有的任何值都将被忽略。 You would need to define a setter to set self.courseA.name if you want to ensure the value can be written to. 如果要确保可以写入该值,则需要定义一个setter来设置self.courseA.name。 You don't need to worry about key-value coding notifications, because they will be triggered by the Core Data Managed Object. 您无需担心键值编码通知,因为它们将由Core Data Managed Object触发。

public class Universtity: NSManagedObject {

    dynamic var name: String {
        get {
            let name = self.courseA?.name
            return name!
        }
        set(newValue) {
            courseA!.name = newValue
        }
    }
}

Also the pattern you have used to force unwrap a non-optional value in your getter isn't optimal. 同样,您用来强制在getter中解开非可选值的模式也不是最佳选择。 I haven't edited this because that is another discussion, but I would suggest asking yourself the question am I sure why I am doing this? 我没有编辑它,因为那是另一次讨论,但是我建议问自己一个问题,我确定为什么要这样做吗? for every "?" 每一个“?” and "!" 和“!” you use. 你用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM