通过另一个ViewController从ViewController获取数据

时间:2018-07-17 13:57:42

标签: ios swift uitableview core-data

我有一个应用程序,其中有三个ViewControllers和一个tableView。它们都是分层的,俱乐部->成员->交易。在memberVC中,俱乐部的所有成员均会显示其姓名和身份。 Saldo是根据起始金额和所有交易金额计算得出的。现在,我要在俱乐部中显示整个俱乐部的收入,该收入是根据所有成员的起始金额和俱乐部中成员的所有交易额计算得出的。我尝试过,但是我的解决方案在(member?.transactions)!部分抛出了此错误:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

这是我的解决方案:

  var transcount = 0.0
        for trans in (member?.transactions)!{
            transcount = trans.money + transcount
       }

        var countmember = 0.0
        for membs in (club.members)! {
            countmember = membs.saldo + countmember
        }

This is my Core-Data model

创建成员的方式如下:

  let member = Member(name: nameTextField.text ?? "", saldo: Double(saldoTextField.text!) ?? 0.0, surname: firstnameTextField.text ?? "")

        do{
            try member?.managedObjectContext?.save()
        } catch {
            print("Could not save member")
        }
        let name = nameTextField?.text
        let surname = firstnameTextField?.text
        let saldoText = saldoTextField?.text ?? ""
        let saldo = Double(saldoText) ?? 0.0

        if let member = Member(name: name, saldo: saldo, surname: surname) {
          club?.addToRawMembers(member)

            do {
                try member.managedObjectContext?.save()

                self.navigationController?.popViewController(animated: true)
            } catch {
                print ("Member couldn't be created")
           }
        }
    }

这是创建交易的方式:

   let transaction = Trancsaction(money: Double(moneyTextField.text!) ?? 0.0, date: datePicker.date , reason: reasonTextField.text ?? "")
        do{
            try transaction?.managedObjectContext?.save()

        } catch{
            print("Could not save transaction")
        }

        let reason = reasonTextField?.text
        let moneyText = moneyTextField?.text ?? ""
        let money = Double(moneyText) ?? 0.00
        let date = datePicker?.date

        if let transaction = Trancsaction(money: money, date: date, reason: reason)   {
           member?.addToRawTransactions(transaction)

            do{
                try transaction.managedObjectContext?.save()

                self.navigationController?.popViewController(animated: true)
            } catch{
                print("Transaction could not be created")
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

您在没有充分理由的情况下强行打开选装件-绝对不要这样做。 membertransactions很可能是nil。因此,使用以下模式将您的代码转换为安全代码:

var transcount = 0.0
if let transactions = member?.transactions {
    for trans in transactions {
        transcount = trans.money + transcount
    }
}