数据未保存在sql lite核心数据库中

问题描述 投票:1回答:1

我为核心数据创建了项目,为它编写了代码,但是它没有将数据保存在sql数据库中。

//  ViewController.swift

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var mobileTextField: UITextField!
@IBOutlet weak var stateTextField: UITextField!


override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}



@IBAction func saveButtonClicked(_ sender: Any) {

    let dict = ["name":nameTextField.text,"email":emailTextField.text,"mobile":mobileTextField.text,"state":stateTextField.text]

    DatabaseHelper.shareInstance.save(object: dict as! [String : String])
}

//MARK: TextField Delagate mthods

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    return true
}

}



//  DatabaseHelper.swift

import Foundation
import UIKit
import CoreData

class DatabaseHelper{

static var shareInstance = DatabaseHelper() //it is required if you want to access following method outside any class

let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext

func save(object:[String:String]){

    let student = NSEntityDescription.insertNewObject(forEntityName: "Student", into: context!) as! Student

    student.name = object["name"]
    student.email = object["email"]
    student.mobile = object["mobile"]
    student.state = object["state"]

    do{

        try context?.save()
    }catch{
      print("daata is not save")
    }

}

}



//AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        print("Document Directory :",FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last ?? "Not Found")

        return true
    }

为了创建核心数据项目,我做了所有必要的代码,但是我无法将数据保存到sql数据库中。

有人可以告诉/帮助我,我在代码中缺少什么吗?

我正在使用Xcode 11.0和5

The complete project you can find here

ios swift core-data
1个回答
0
投票

使用以下代码打印(获取)您的数据。

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Student")

        request.returnsObjectsAsFaults = false
        do {
            let result = try context.fetch(request)
            for data in result as! [NSManagedObject] {
               print(data.value(forKey: "name") as! String)
          }

        } catch {

            print("Failed")
        }
© www.soinside.com 2019 - 2024. All rights reserved.