Я видел, как другие пользователи спрашивают об этом, но я не понимаю там кода, так как я новый пользователь для iOS и xcode. Я реализовал добавление пользователей в качестве основных данных, но я не уверен, как я могу обновить записи. Я хочу иметь возможность либо выбрать пользователя, уже находящегося в системе, либо ввести его идентификатор, а затем обновить остальные записи. Вот мои данные для контроллера 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")
}
}