How to set an initial value for @NSManaged propert

2019-05-06 12:39发布

问题:

I have a subclass of PFObject called Attendee. In this class, there is a instance variable I have called isFavorite. Below is its class definition:

@NSManaged var isFavorite: Bool

This is an instance var that is local to the device and I never sync it up to the server. In addition, I never explicitly instantiate the Attendee class, but rather create it by typecasting from PFObject. I would like to set the above var to have an initial value of false. How would I achieve this?

回答1:

var isFavorite: Bool {
    get {
        if let isFavorite = self["isFavorite"] as? Bool {
            return isFavorite
        }
        return false //default
    }
    set {
        self["isFavorite"] = newValue
    }
}