如何更新/编辑核心数据

时间:2018-11-04 23:34:43

标签: swift xcode core-data

我已经看到其他用户问过这个问题,但是由于我是iOS和xcode的新用户,所以我对代码不了解。我已经实现了将用户添加为核心数据的操作,但是我不确定如何更新记录。我希望既可以选择系统中已经存在的用户,也可以输入其ID,然后更新其余记录。这是我关于UIView Controller的数据。

$ ./lookup 
Sum of binary digits for numbers in range [0, 4294967295]: 133143986178
Time: 0.000282s

这是我的AppDelegate.swift文件代码:

import UIKit

class AddScreen: UIViewController {
@IBOutlet weak var studentID: UITextField!
@IBOutlet weak var firstName: UITextField!
@IBOutlet weak var lastName: UITextField!
@IBOutlet weak var age: UILabel!
@IBOutlet weak var stepper: UIStepper!
@IBOutlet weak var courseStudy: UITextField!
@IBOutlet weak var address: UITextField!
@IBOutlet weak var controller: UISegmentedControl!
@IBOutlet weak var gender: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    stepper.wraps = true
    stepper.autorepeat = true
    stepper.maximumValue = 99
}

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

@IBAction func stepperchanged(_ sender: UIStepper) {
    let step = Int(stepper.value)
    age.text = String(step)
}

@IBAction func segController(_ sender: Any) {
    if controller.selectedSegmentIndex == 0 {
        gender.text = "Male"
    }
    if controller.selectedSegmentIndex == 1 {
        gender.text = "Female"
    }
}

@IBAction func addStudent(_ sender: Any) {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.storeStudentInfo(studentID: Int(studentID.text!)!, firstName: firstName.text!, lastName: lastName.text!, gender: gender.text!, courseStudy: courseStudy.text!, age: Int(age.text!)!, address: address.text!)
    studentID.text = ""
    firstName.text = ""
    lastName.text = ""
    courseStudy.text = ""
    age.text = "0"
    address.text = ""
}

@IBAction func editStudent(_ sender: Any) {
    //Update student here?
}

1 个答案:

答案 0 :(得分:0)

首先,请勿为此使用AppDelegate。您希望StudentManager管理学生的CRUD。

所以我会做这样的事情:

import Foundation
import UIKit
import CoreData

class StudentManager {

   func createStudent(_ name: String, address: String) {

       let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
       let entity_student =  NSEntityDescription.entity(forEntityName: "Student", in:managedContext)

       let student = Student(entity: entity_student!, insertInto: managedContext)

       student.name = name
       student.address = address

       do {
           try managedContext.save()
       } catch let error as NSError  {
           print("Could not save \(error), \(error.userInfo)")
       }
   }

   func removeAllStudents() {

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

       let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Student")
       fetchRequest.includesPropertyValues = false

       do {
           let students = try managedContext.fetch(fetchRequest) as! [Student]

           for student in students {
               managedContext.delete(student)
           }

           try managedContext.save()

       } catch let error as NSError  {
           print("Could not delete \(error), \(error.userInfo)")
       }
   }

   func removeStudent(_ student: Student) {

       let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
       managedContext.delete(student)

       do {
           try managedContext.save()

       } catch let error as NSError  {
           print("Could not delete \(error), \(error.userInfo)")
       }
   }

   func updateStudent(_ student: Student, name: String, address: String) {

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

       student.name = name
       student.address = address

       do {
           try managedContext.save()
       } catch let error as NSError  {
           print("Could not save \(error), \(error.userInfo)")
       }
   }
}

您可以在AddScreen中使用

let studentManager = StudentManager()
studentManager.createStudent("aName", address: "anAddress")

因此无需在AppDelegate中编写代码

如您所见,您可以仅通过更改实体的属性值并保存将其编辑。

通常,您会在表格视图中有一个由[Student]之类的学生对象提供的学生列表。

您需要将选定的学生对象传递到EditScreen(或其他任何对象)。

如果您有学生,可以使用以下方法轻松进行更新:

var student: Student! // passed from table view

@IBAction func editStudent(_ sender: Any) {
    //Update student here?
    let studentManager = StudentManager()
    studentManager.updateStudent(student, name: "anotherName", address: "AnotherAddress")
}