试图在两个视图控制器之间传递核心数据

时间:2018-07-11 23:27:15

标签: swift uitableview core-data segue

所以我现在刚刚熟悉Core Data并通过Raywenderlich.com在2个VC之间传递数据,我有点陷入一个简单的项目中。到目前为止,我已经能够做一些我想做的事,但是我遇到了一个错误-我知道是什么原因造成的,但是不确定如何解决。

基本上,我有两个视图控制器:(1)显示在UITableView上添加到列表的所有项目,以及(2)将项目添加到表视图的选项。

这是我的主视图控制器:

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource, 
UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!

private var finalItems:[Shoe] = []
var finalName = ""
var finalBuy = ""
var finalSell = ""
var finalFee = ""

private var appDelegate = UIApplication.shared.delegate as! AppDelegate

private var managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext


//MARK: Functions
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return finalItems.count
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "ShoeCell", for: indexPath) as! CustomCells
    let shoe = finalItems[indexPath.row]

    cell.Name.text = "Name: \(shoe.name!)"
    cell.buyPrice.text = "Age: $\(shoe.buyPrice!)"
    cell.sellPrice.text = "Height: $\(shoe.sellPrice!)"
    cell.transFee.text = "Gender: \(shoe.fee!)"

    return cell
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    let nameToSave = finalName
    let buyToSave = finalBuy
    let sellToSave = finalSell
    let feeToSave = finalFee

    let shoe = Shoe(entity: Shoe.entity(), insertInto: managedContext)
    shoe.name = nameToSave
    shoe.buyPrice = buyToSave
    shoe.sellPrice = sellToSave
    shoe.fee = feeToSave

    if(finalName != "" && finalBuy != "" && finalSell != "" && finalFee != ""){

    do {
        try managedContext.save()
        appDelegate.saveContext()
        finalItems.append(shoe)
    } catch let error as NSError {
        print("Error saving: \(error)")
        }

    }

    // Fetch a request to retrieve the data again
    do {
        finalItems = try managedContext.fetch(Shoe.fetchRequest())
    } catch let error as NSError {
        print("Error fetching request: \(error)")
    }

}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    tableView.reloadData()
}

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.dataSource = self
    tableView.delegate = self
}

}

基本上,我有这样一个思考过程:数据通过segue传递之后,它将首先检查数据字段是否为空白(因此为If-Statement)。如果为空,则不会将任何数据追加到数组,也不会将任何内容保存到核心数据。向前迈进,既然什么都没有保存,那么就不应该获取任何内容,从而使表格视图不受影响。

实际上发生的是,每次我运行该应用程序时,都会发生完全相反的事情:我收到文本但没有数据,我相信这是因为我将finalName设置为"",依此类推。

这是另一个实际上添加项的视图控制器:

class AddViewController: UIViewController {

private var shoeItems:[Shoe] = []
var addName = ""
var addBuy = ""
var addSell = ""
var addFee = ""

@IBOutlet weak var nameText: UITextField!
@IBOutlet weak var buyText: UITextField!
@IBOutlet weak var sellText: UITextField!
@IBOutlet weak var feeText: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func addItem(_ sender: Any) {

    self.addName = nameText.text!
    self.addBuy = buyText.text!
    self.addSell = sellText.text!
    self.addFee = feeText.text!

    performSegue(withIdentifier: "addShoe", sender: self)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! ViewController
        vc.finalName = self.addName
        vc.finalBuy = self.addBuy
        vc.finalSell = self.addSell
        vc.finalFee = self.addFee
}
}

如果只是一个标签,我就可以成功地将数据传递给另一个VC,但是在添加数组以填充UITableView时,这让我感到困惑。我尝试了其他解决方案(失败的解决方案),例如使用全局数组并通过segue传递数组,但这似乎行不通。

0 个答案:

没有答案