gpt4 book ai didi

ios - 快速更新核心数据实体中的数据

转载 作者:行者123 更新时间:2023-11-28 06:20:14 24 4
gpt4 key购买 nike

我正在尝试设置一个函数来更新我的核心数据实体中的数据。我可以调出一个特定的上下文并更改数据,但是当我单击“保存”时,它会创建一个新的上下文而不是覆盖旧的。我的代码如下:

导入 UIKit导入核心数据

类 RoomDetailTableViewController:UITableViewController、UINavigationControllerDelegate、UIImagePickerControllerDelegate {

@IBOutlet weak var roomImageView: UIImageView!
@IBOutlet weak var roomNameTextField: UITextField!


@IBOutlet weak var rmLengthFt: UITextField!
@IBOutlet weak var rmLengthInches: UITextField!
@IBOutlet weak var rmWidthFt: UITextField!
@IBOutlet weak var rmWidthInches: UITextField!

let appDelegateObj : AppDelegate = UIApplication.shared.delegate as! AppDelegate


var managedObjectContext: NSManagedObjectContext? {
return (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
}

var roomArray = [Rooms]()
var arrayElement: Int = 0

override func viewDidLoad() {
super.viewDidLoad()
retrieveRooms()
setSaveBarButton()
if arrayElement != 2112 { //Kludgy******

updateRoom()
}

}


func setSaveBarButton(){

let saveBarButton = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(RoomDetailTableViewController.saveRoom))
navigationItem.rightBarButtonItem = saveBarButton



}

func updateRoom(){
let room = self.roomArray[arrayElement]


self.roomNameTextField.text = room.roomName
self.roomImageView.image = UIImage(data: room.roomImage! as Data)

}


@IBAction func pickRoomImage(_ sender: UITapGestureRecognizer) {


let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.allowsEditing = true

let alertController = UIAlertController(title: "Add a Picture", message: "Choose From", preferredStyle: .actionSheet)

let cameraAction = UIAlertAction(title: "Camera", style: .default) { (action) in
pickerController.sourceType = .camera
self.present(pickerController, animated: true, completion: nil)

}
let photosLibraryAction = UIAlertAction(title: "Photo Library", style: .default) { (action) in
pickerController.sourceType = .photoLibrary
self.present(pickerController, animated: true, completion: nil)

}

let savedPhotosAction = UIAlertAction(title: "Saved Photos Album", style: .default) { (action) in
pickerController.sourceType = .savedPhotosAlbum
self.present(pickerController, animated: true, completion: nil)

}

let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)

alertController.addAction(cameraAction)
alertController.addAction(photosLibraryAction)
alertController.addAction(savedPhotosAction)
alertController.addAction(cancelAction)


present(alertController, animated: true, completion: nil)

}


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.dismiss(animated: true, completion: nil)

if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.roomImageView.image = image

}
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}

func saveRoom(){

if roomNameTextField.text!.isEmpty || roomImageView.image == nil {

let alertController = UIAlertController(title: "Room Name", message: "Pleae provide data", preferredStyle: .alert)

alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)


} else {

//Let's save
if let moc = managedObjectContext {
let room = Rooms(context: moc)
room.roomName = roomNameTextField.text!
room.rmLengthFt = rmLengthFt.text!
room.rmLengthInches = rmLengthInches.text!
room.rmWidthFt = rmWidthFt.text!
room.rmWidthInches = rmWidthInches.text!

if let data = UIImageJPEGRepresentation(self.roomImageView.image!, 1.0) {
room.roomImage = data as NSData
}

saveToCoreData() {
self.navigationController!.popToRootViewController(animated: true)
}


}
}

}


func saveToCoreData(completion: @escaping ()->Void){
managedObjectContext!.perform {

var error: NSError?
do {
try self.managedObjectContext?.save()
completion()
} catch let error1 as NSError {
error = error1
}

//Check for any errors

if let err = error {

let a = UIAlertController(title: "Error", message: err.localizedFailureReason, preferredStyle: .alert)
self.present(a, animated: true)
} else {


print("Room saved to CoreData")

}

}

}

func retrieveRooms(){
fetchRoomsFromCoreData { (rooms) in
if let rooms = rooms{
self.roomArray = rooms
self.tableView.reloadData()
}
}
}

func fetchRoomsFromCoreData(completion: ([Rooms]?)->Void){
var results = [Rooms]()
let request: NSFetchRequest<Rooms> = Rooms.fetchRequest()
do {
results = try managedObjectContext!.fetch(request)
completion(results)
}catch {
print("Could not fetch Rooms from CoreData:\(error.localizedDescription)")
}
}

我知道我的命名法可能不准确,因为我刚刚开始学习使用核心数据。

如有任何帮助,我们将不胜感激。

最佳答案

我相信您的意思是当您希望修改现有实体时,您正在创建一个新实体。而不是

let room = Rooms(context: moc)

它正在创建一个新实体,您想要访问您用来填充数据的同一个实体。类似于 let room = self.roomArray[arrayElement]。很难进一步评论,因为我不理解您的代码或您身上发生了什么邪恶导致数字 2112 被诅咒。 (if arrayElement != 2112 WTF!)

关于ios - 快速更新核心数据实体中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43851662/

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