Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 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 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...