swift - Realm 导致程序出现意外行为。 (OS X 和 Swift)

标签 swift cocoa realm

所以我正在使用 Realm 作为数据库创建一个相当简单的程序。我对 Swift(或任何 OS X 或 iOS 环境)编程相当陌生。在我的程序中,当按下按钮时 IBAction func createInvoice 我希望发生一些事情,我想计算之前的情况数据库中的行并创建发票号码,我想将新数据写入数据库,我想调用新的 View 和 View Controller 并传递发票号码。我的代码可以工作,除了一件事之外,当使用 Realm 时,在创建发票编号之前调用新 View Controller (override funcprepareForSegue),以便将 0 值传递到新 View Controller 。

如果我创建一个虚拟发票编号值,例如 let Invoicenumber = 42 一切都会完美运行。看来 Realm 导致事情发生“无序”,我怎样才能让 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 不同的线程上,您必须刷新 Realm (Realm().refresh()) >) 在访问您的 invoicenumber 变量(我假设其类型为 RealmSwift.Object)之前。

关于swift - Realm 导致程序出现意外行为。 (OS X 和 Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31735167/

相关文章:

Swift nil 有数值吗?

objective-c - 弹出菜单定位项 :atLocation:inView: hangs when switching to another application

objective-c - 如何在 cocoa/iOS 中进行 SHA 哈希

ios - Swift 中 Realm 查询的交叉引用谓词

android - 我的数据库中的搜索过滤器有问题

ios - 使用 Swift 访问 Microsoft Face API IOS

ios - 如何在不包装旧库的情况下让 OAuth2 与 SwiftUI 一起使用?

ios - 如何在 Parse 中获取具有对象 ID 数组的对象

objective-c - 创建自定义 NSWindow 界面

Swift/Realm 仅在提供的数组中添加最后一个对象 (SwiftyJSON)