【问题标题】:How to update/edit core data如何更新/编辑核心数据
【发布时间】:2019-04-08 08:23:38
【问题描述】:

我看到其他用户问过这个问题,但我不明白那里的代码,因为我是 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")
    }
}

【问题讨论】:

    标签: swift xcode core-data


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多