Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

iOS - Swift and Parse error regarding Optionals within Subclass

I have implemented a Parse subclass called Filler.swiftthat contains five variables that are held in the Parse backend.

Whilst trying to save data to the Parse backend using this subclass I get the error: fatal error: unexpectedly found nil while unwrapping an Optional value.

This is the code that brings about the error (on the self.object.username = username line):

if let username = PFUser.currentUser()?.username {

        // set username equal to current user
        self.object.username = username

    }else{

        println("PFUser.currentUser()?.username contained a nil value.")

    }

I've figured out that it's something to do with how I'm handling optional variables in my subclass but the Parse documentation isn't clear on exactly how to do this. Here's my code for the subclass:

class Fillup : PFObject, PFSubclassing {

var amount : String? {

    get {

        return self["amount"] as? String

    }

    set{

        self["amount"] = newValue

    }

}

var cost : String? {

    get {

        return self["cost"] as? String

    }

    set{

        self["cost"] = newValue

    }

}


var date : NSDate {

    get {

        return self["date"] as! NSDate

    }

    set{

        self["date"] = newValue

    }

}

var username: String? {

    get{

        return self["username"] as? String

    }

    set {


        self["username"] = newValue

    }
}


var id : Int?{

    get {

        return self["id"] as? Int

    }

}

override class func initialize() {

    var onceToken : dispatch_once_t = 0;

    dispatch_once(&onceToken) {

        self.registerSubclass()

    }

}

class func parseClassName() -> String {

    return "Fillup"
}

}

Any help would be really appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Did you try adding a ? like so: self.object?.username = username


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...