导致程序行为异常的领域。 (OS X 和 Swift)

Realm causing program to behave unexpectedly. (OS X and Swift)

所以我正在创建一个相当简单的程序,使用 Realm 作为我的数据库。我对 Swift(或任何 OS X 或 iOS 环境中的编程相当陌生。)在我的程序中,当按下按钮时 IBAction func createInvoice 我希望发生一些事情,我想计算数据库中的前几行并创建一个发票号,我想将新数据写入数据库,我想调用一个新的视图和视图控制器并传递发票号。当使用 Realm 时,我的代码可以正常工作,在创建发票编号之前调用新的视图控制器 (override func prepareForSegue),因此将 0 值传递给新的视图控制器。

如果我创建一个虚拟发票编号值,例如 let invoicenumber = 42,一切都会完美无缺。似乎是 Realm 导致了事情的发生 'out of order' 如何让 veiwcontroller 在加载之前等待一个值?

@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)
}
} 

如果 createInvoice 发生在与 prepareForSegue 不同的线程上,您必须在访问 invoicenumber 变量(其中我假设是 RealmSwift.Object).

类型

我已经解决了这个问题,感谢@Shmidt 的帮助,使用 Realm 的内置通知中心。要使用通知,您可以使用这个基本结构。

var notificationToken: NotificationToken?

deinit{
let realm = Realm()
if let notificationToken = notificationToken{
    realm.removeNotification(notificationToken)
}
}

override func viewDidLoad() {
super.viewDidLoad()
let realm = Realm()
notificationToken = realm.addNotificationBlock { note, realm in
   println("The realm is complete")
}
...
}

我的代码中的另一个小错误是 let invoicenumber = a + invoicenraw 我需要删除 let,因为它是一个变量而不是常量。