将核心数据值传递到文本字段以进行编辑/保存

时间:2017-10-15 04:24:41

标签: ios swift uitableview core-data

我是使用Xcode和swift并且还在学习的新手。我无法将核心数据从实体传递到文本字段/标签,然后用户可以选择编辑和保存记录。我的目标是当用户从friendslistViewController.swift点击tableView中的单元格时,然后将它们带到editViewController.swift屏幕以编辑并保存记录。我想我需要实现prepareforsegue函数,但不确定如何?

friendsViewController.swift (初始数据输入)

//
//  friendsViewController.swift
// 
//
//  Created by on 11/10/17.
//  Copyright © 2017. All rights reserved.
//

import UIKit
import CoreData

class friendsViewController: UIViewController {

        //OUTLETS


    @IBOutlet weak var firstName: UITextField!        
    @IBOutlet weak var lastName: UITextField!        
    @IBOutlet weak var genderSegControl: UISegmentedControl!        
    @IBOutlet weak var ageStepper: UIStepper!

    //AGECOUNT
    @IBOutlet weak var ageLabel: UILabel!        
    @IBOutlet weak var address: UITextField!

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

    override func viewDidLoad() {
        super.viewDidLoad()    
        // Do any additional setup after loading the view.
    }

    //actions

    @IBAction func ageStepperStep(_ sender: UIStepper) {
        let step = Int(sender.value) // using an integer variable
        ageLabel.text = String(step)
        // label1.text = Int(sender.value).description
        // another way without using any integer variable
    }


    // TEST GENDER
    /*

        var gender : String
        if self.genderSegControl.selectedSegmentIndex == 0 {
            gender = "male"
        }
        else {
            gender = "female"
        }
        genderLabel.text! = gender

 */

   //SAVE FRIEND BUTTON
    @IBAction func saveFriendBtn(_ sender: Any) {

        if firstName.text != "" && lastName.text != "" {               

            var gender : String?
            if self.genderSegControl.selectedSegmentIndex == 0 {
                gender = "male"
            }
            else {
                gender = "female"
            }


            let newFriend = NSEntityDescription.insertNewObject(forEntityName: "Friends", into: context)
            newFriend.setValue(self.firstName.text, forKey: "firstName")
            newFriend.setValue(self.lastName.text, forKey: "lastName")
            newFriend.setValue(self.address.text, forKey: "address")
            newFriend.setValue(self.ageLabel.text, forKey: "age")
            newFriend.setValue(gender, forKey: "gender")

            /*let gender: String = genderSegControl.titleForSegment(at: genderSegControl.selectedSegmentIndex)!
 */


            //SAVE THE CONTEXT
            do {
                try context.save()
            }
            catch{
                print(error)
            }
         }
        else {
            print("please enter your first and last name!")
        }
    }

} //end class

friendslistViewController.swift (显示带有单元格的tableView的屏幕)

//
//  friendslistViewController.swift
// 
//
//  Created by on 11/10/17.
//  Copyright © 2017. All rights reserved.
//

import UIKit
import CoreData

class friendslistViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    /*
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        var DestViewController : editViewController = segue.destinationViewController as! editViewController

        DestViewController.firstNameInput = name.firstName!
    }
 */

    //outlets

    @IBOutlet weak var tableView: UITableView!

    var userArray:[Friends] = []

    override func viewDidLoad() {
        super.viewDidLoad()            

        tableView.delegate = self
        tableView.dataSource = self

        self.fetchData()
        self.tableView.reloadData()


        // Do any additional setup after loading the view.
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return userArray.count
    }


    //DISPLAY LISTVIEW
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        //save first users data into array
        let name = userArray[indexPath.row]
        cell.textLabel!.text = name.firstName! + " " +
            name.lastName! + ", " +
            name.age! + ", " +
            name.gender! + ", " +
            name.address!

        return cell
    }


    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        if editingStyle == .delete{

            //delete a friend
            let friend = userArray[indexPath.row]
            context.delete(friend)
            (UIApplication.shared.delegate as! AppDelegate).saveContext()

            do{
                userArray = try context.fetch(Friends.fetchRequest())

            }catch{
                print(error)
            }

        }
        tableView.reloadData()

    }

    //fetch the data
    func fetchData(){
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        do{
            userArray = try context.fetch(Friends.fetchRequest())
        }
            //if error exists/catch it
        catch{
            print(error)
        }
    }

    //actions
 } //end class

editViewController.swift (处理编辑/保存的屏幕)

//
//  editViewController.swift
// 
//
//  Created by  on 15/10/17.
//  Copyright © 2017. All rights reserved.
//

import UIKit

import CoreData

class editViewController: UIViewController {

    @IBOutlet weak var firstName: UITextField!        
    @IBOutlet weak var lastName: UITextField!        
    @IBOutlet weak var ageLabel: UILabel!        
    @IBOutlet weak var address: UITextField!

    var firstNameInput = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        firstName.text = firstNameInput

        // Do any additional setup after loading the view.
    }

 }

2 个答案:

答案 0 :(得分:0)

首先,您应该更改视图控制器的名称,以便它们都以大写字母(例如class FriendsViewController: UIViewController)开头,并对文件名执行相同的操作。

其次,你需要添加一个segue是正确的。您是否在Apple的文档中查看了func prepare(for segue: UIStoryboardSegue, sender: Any?)

您需要在目标视图控制器(editViewController.swift)中使用可以为其分配Friend对象的变量。在prepare(for:sender:)方法中,您需要let destinationViewController = segue.destination as! EditViewController之类的内容。然后,您可以使用该destinationViewController变量访问目标视图控制器中的变量,并将对象分配给它。

了解你能走多远。

答案 1 :(得分:0)

代码更改:

1。 friendslistViewController.swift

//Change this to match your segue
private let showEditSegueID = "Edit Friend" 

private var selectedIndexPath : IndexPath?

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    selectedIndexPath = indexPath

    performSegue(withIdentifier: showEditSegueID, sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    switch segue.identifier {

    case .some(showEditSegueID):

        if let editViewController = segue.destination as? editViewController,
            let selectedIndexPath = selectedIndexPath {

            let friend = userArray[selectedIndexPath.row]
            editViewController.friend = friend
        }

    default:
        break
    }
}

2。 editViewController.swift

weak var friend : Friends?

建议:

  1. 确保类名以大写字母
  2. 开头
  3. 让核心数据实体名称为单数,以便它代表它所拥有的每个记录。
  4. 在开始构建应用之前了解基础知识。
  5. 学习基础课程最初需要时间,但随着时间的推移会给你带来很多麻烦。
  6. 了解:

    1. 学习Swift语言
    2. 了解构建应用
    3. 了解核心数据
    4. 的参考文献: