gpt4 book ai didi

swift - 如何更新/编辑核心数据

转载 作者:搜寻专家 更新时间:2023-11-01 05:32:37 25 4
gpt4 key购买 nike

我看到其他用户问过这个问题,但我不明白那里的代码,因为我是 iOS 和 xcode 的新用户。我已经实现了将用户添加为核心数据,但我不确定如何更新记录。我希望能够选择系统中已有的用户或输入他们的 ID,然后更新他们的其余记录。这是我的 UIView Controller 数据。

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 来管理 Student 的 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 中编写代码

如您所见,只需更改实体的属性值并保存即可编辑实体。

通常情况下,您在 TableView 中有一个学生列表,这些学生对象由 [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")
}

关于swift - 如何更新/编辑核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53146551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com