如何更新/编辑核心数据



我看到其他用户问这个问题,但我不理解那里的代码,因为我是iOS和xcode的新用户。我已经实现了将用户添加为核心数据,但我不确定如何更新记录。我希望能够选择已经在系统中的用户,或者键入他们的ID,然后更新他们记录的其余部分。这是我的UIView控制器数据。

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?
}

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

func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error (nserror), (nserror.userInfo)")
}
}
}
func getContext () -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate
as! AppDelegate
return
appDelegate.persistentContainer.viewContext
}
func storeStudentInfo (studentID: Int, firstName: String, lastName: String, gender: String, courseStudy: String, age: Int, address: String) {
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "Student", in: context)
let transc = NSManagedObject(entity: entity!, insertInto: context)
transc.setValue(studentID, forKey: "studentID")
transc.setValue(firstName, forKey: "firstName")
transc.setValue(lastName, forKey: "lastName")
transc.setValue(gender, forKey: "gender")
transc.setValue(courseStudy, forKey: "courseStudy")
transc.setValue(age, forKey: "age")
transc.setValue(address, forKey: "address")
do {
try context.save()
} catch let error as NSError {
print("Could not save (error), (error.userInfo)")
} catch { }
}
func getStudentInfo () -> String {
var info = ""
let fetchRequest: NSFetchRequest<Student> = Student.fetchRequest()
do {
let searchResults = try getContext().fetch(fetchRequest)
for trans in searchResults as [NSManagedObject] {
let studentID = String(trans.value(forKey: "studentID") as! Int)
let firstName = trans.value(forKey: "firstName") as! String
let lastName = trans.value(forKey: "lastName") as! String
let gender = trans.value(forKey: "gender") as! String
let courseStudy = trans.value(forKey: "courseStudy") as! String
let age = String(trans.value(forKey: "age") as! Int)
let address = trans.value(forKey: "address") as! String
info = info + studentID + ", " + firstName + ", " + lastName + ", " + gender  + ", " + courseStudy + ", " + age + ", " + address + "n" + "n"
}
} catch {
print("Error with request: (error)")
}
return info;
}
func removeRecords () {
let context = getContext()
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Student")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try context.execute(deleteRequest)
try context.save()
} catch {
print ("There was an error")
}
}

首先,不要使用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")
}

最新更新