Dan DeLuca
Dan DeLuca

Reputation: 117

Making a prepareForSegue wait till after a Realm database write is completed

In my program when a button is pressed I am adding information to a database, including creating invoice number then calling a segue to a new view controller. When the new view controller is called I'd like to pass along that invoice number. Everything works fine, I can pass along sample data no problem. However, it appears that "override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject!) {}" is being called before my button (upon initialization of the view controller?), so I am passing along a blank value. How can I make my prepareForSegue wait till after my button is pressed? Here is the code I currently have.

@IBAction func createInvoice(sender: AnyObject) {
     let realm = Realm()
    let invoicepull = Invoice()
    let invoicecount = realm.objects(Invoice)
    let invoicenraw = invoicecount.count
    let a = 100
    let invoicenumber = a + invoicenraw
    var invoicefile = Invoice()
    invoicefile.inumber = invoicenumber
    invoicefile.cnumber = clientcombo.stringValue
    invoicefile.cost = owed.doubleValue
    invoicefile.paid = paid.doubleValue
    invoicefile.sevicecode = service.stringValue
    invoicefile.dateofservice = NSDate()
    // Save your object
    realm.beginWrite()
    realm.add(invoicefile)
    realm.commitWrite()
    //Sent notification
    performSegueWithIdentifier("cinvoiceseuge", sender: nil)
 println("Inside Action")
    println(invoicenumber)
    dismissViewController(self)
}

override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject!) {
    if (segue.identifier == "cinvoiceseuge") {
        //Checking identifier is crucial as there might be multiple
        // segues attached to same view
        var detailVC = segue.destinationController as! invociegenerator;
        detailVC.toPass = invoicenumber
        println("Inside Sugue")
        println(invoicenumber)
    }
} 

Update: I belive this is an issue with the Realm database causing it to behave unexpectedly. If I remove all realm code, the program works as expected and I can pass a static dummy value.

Upvotes: 0

Views: 307

Answers (1)

tom.e.kid
tom.e.kid

Reputation: 121

invoicenumber in createInvoice() is a local variable and invoicenumber in prepareForSegue() seems to be an instance variable. is it what you expected?

Upvotes: 0

Related Questions