从CoreData中的TextField保存并获取

时间:2019-02-10 03:25:51

标签: swift core-data save fetch

我想保存并从TextField中获取数据。我的代码如下:

import UIKit
import CoreData

class DetailViewController: UIViewController, UITextViewDelegate {
private var currentTextField: UITextField?

var Detail: [NSManagedObject] = [ ]

@IBOutlet weak var TableViewDetail: UITextView!   
@IBOutlet weak var LabelDetail: UILabel!  
@IBOutlet weak var TextField: UITextField!  

保存按钮:

@IBAction func SaveButton(_ sender: Any) {    
    if (TextField.text ==  "") {
        self.save2(TextField.text!)
    }

    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}
    let managedContext = appDelegate.persistentContainer.viewContext

    do {

        try managedContext.save()

    } catch let err as NSError {
        print("Cant save arrangement", err)
    }

    print("TextFieldEditingEnd2")
}

这有必要吗?

@IBAction func Submit(sender: UIButton) {
    if let currentTextField = currentTextField {
        currentTextField.resignFirstResponder()
    }
}

我认为这是生成的错误:

func textFieldDidEndEditing(_ textField: UITextField) {
    if (TextField.text !=  "")
    {
        currentTextField = textField
        print("TextFieldEditingEnd2")
        if  CoreDataHandler.saveDetail(itemDetail: (currentTextField?.text!)!) {
        for item in CoreDataHandler.fetchDetail()!  {
            print("\(String(describing: item.itemDetail))")
            }}
    }
}


override func viewDidLoad() {
    super.viewDidLoad()

    TextField.delegate = self as? UITextFieldDelegate
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
    // func viewDidload(_ animated: Bool) {    
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    // User finished typing (hit return): hide the keyboard.
    textField.resignFirstResponder()
    return true
}

保存功能

func save2(_ itemName: String){

    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    let managedContext = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "ItemDetail", in: managedContext)!
    let showItemDetail = NSManagedObject(entity: entity, insertInto: managedContext)

    showItemDetail.setValue(itemName, forKey: "itemDetail")

    do {
        try managedContext.save()
    } catch let err as NSError {
        print("Failed to save item",err) 
    }

}

有错误

  

[SmallApps.DetailViewController TextFieldIO:]:无法识别的选择器   发送到实例0x7fad6de3dc10'

***首先抛出调用堆栈:“

有人建议吗?

编辑: 保存和提取功能:

保存:

class func saveDetail(itemDetail: String) -> Bool {
    let context = getContext()
    let entity = NSEntityDescription.entity(forEntityName: "ItemDetail", in: context)
    let manageObject = NSManagedObject(entity: entity!, insertInto: context)
    manageObject.setValue(UITextField.self, forKey: "itemDetail")
    do {
        try context.save()
        return true
    }catch {
        return false
    }
}

获取:

class func fetchDetail() -> [ItemDetail]? {
    let context = getContext()
    var showItemDetail:[ItemDetail]? = nil
    do {
        showItemDetail = try context.fetch(ItemDetail.fetchRequest())
        return showItemDetail
    }catch {
        return showItemDetail
    }
}

1 个答案:

答案 0 :(得分:0)

保存 itemDetail ,而不保存 UITextField 本身。

对于:textFieldDidEndEditing调用CoreHandler.saveDetail

使用一种保存功能

 func saveDetail(itemDetail: String) {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return false }
    let context = appDelegate.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "ItemDetail", in: context)
    let manageObject = NSManagedObject(entity: entity!, insertInto: context)
    manageObject.setValue(itemDetail, forKey: "itemDetail")
    do {
        try context.save()
    } catch {
        .. handle catch
    }
}

对于正在调用SaveButton函数的save2()。 您没有在 SaveButton

中保存任何内容
@IBAction func SaveButton(_ sender: Any) { 
    // You are comparing TextField.text == "" and saving? If text is not empty you are trying to save. So use != 
    if let text = TextField.text, text != "" { 
        saveDetail(itemDetail: text)
    }  
}

一些建议:

  1. 您的变量名称违反了快速准则。请用 camelCase
  2. 请勿对变量使用!(强制强制转换),而是通过 if guard 语句使用可选链接。
  3. 您从很多地方都在储蓄。遵循 DRY 原则。有一个API可保存到CoreData。
  4. saveDetail 不应返回布尔值。违反 Command-Query 分隔。