Satre
Satre

Reputation: 1744

Using constructors to init instance vars subclass PFObject

I am working on implementing a subclass of PFObject called Event, in Swift. I followed the subclassing guide in Parse's docs, but I don't understand how and where to write the code that adds data to the ivars. Below is my what I have in my class so far, including the ivars.

@NSManaged var name:String
@NSManaged var time:NSDate
@NSManaged var favorite:Bool
@NSManaged var moderator: String
@NSManaged var speakers: [String] 

@NSManaged var slides: PFFile?

@NSManaged var files: [PFFile]?

override class func initialize() {
    var onceToken : dispatch_once_t = 0;
    dispatch_once(&onceToken) {
        self.registerSubclass()
    }        
}

class func parseClassName() -> String! {
    return "Event"
}

Normally, I would implement an init() constructor or something similar. However, I realized that the data would already be contained in the PFObject's dictionary when it is fetched from the server. Where would I put the code to copy across and put this data in the instance vars from the PFObject's dictionary? This is presuming that I would instantiate the object via a query and fetch from the server and not locally using the object() method.

Upvotes: 0

Views: 147

Answers (2)

T. Gallo
T. Gallo

Reputation: 1

You don't have to copy manually. That's the Parse framework job. The objects will be populated with data after a fetch.

Upvotes: 0

Satre
Satre

Reputation: 1744

Based on the comment by deadbeef above, I realized that I can just use Swift's getters and setters for computed properties to read and write values from the PFObject's data dictionary. For example a property that I intend to have as read-only:

var name:String
{
    return self["name"] as String
}

And a property I intend to have as read-write

var favorite:Bool 
{
    get {
        return self["favorite"] as Bool
    }
    set(value) {
        self["favorite"] = value
    }
}

Upvotes: 1

Related Questions