简体   繁体   中英

Get the object id when the object is created (Parse.com)

I would like to set the string value to the object id when I create the object below. At the moment it prints "nil". Any ideas? Thanks

    var date:NSDate = currentDatePicker.date
    var DOB:NSDate = DOBPicker.date

    var user = PFUser.currentUser()

    var report = PFObject(className:"reports")
    report["name"] = nameTextField.text
    report["DOB"] = DOB
    report["date"] = date
    report["user"] = user
    report.saveInBackground()

    var ojId = report.objectId
    println(ojId)

saveInBackground is an asynchronous method, so it doesn't wait. The reason why the id is not set is because the entity has not been saved yet.

I think you should use saveInBackgroundWithBlock: and retrieve the object id form within the block (which is executed after the entity has been saved):

var report = PFObject(className:"reports")
report["name"] = nameTextField.text
report["DOB"] = DOB
report["date"] = date
report["user"] = user
report.saveInBackgroundWithBlock { (success, error) -> Void in
    if success {
        var ojId = report.objectId
        println(ojId)
    }
}

or maybe also save , which is performed synchronously - but do not use that from the main thread:

report.save()
var ojId = report.objectId
println(ojId)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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