如何创建CoreData数据库swift4

时间:2017-12-06 09:47:19

标签: ios core-data swift4

请分享一些示例代码段以获取数据库保存详细信息并在swift 4中获取已保存的详细信息

4 个答案:

答案 0 :(得分:1)

这是我的回答

步骤1:创建Coredata Stack Class,见下文

var coreDataStack:CoreDataStack = CoreDataStack()//在appDelegate上添加此行

    class Stack
    {
    lazy var managedObjectModel: NSManagedObjectModel = {
    let modelUrl = Bundle.main.url(forResource: "Model", withExtension: "momd")!
    return NSManagedObjectModel(contentsOf: modelUrl)!
}()


lazy var peristentStoreCoordinator: NSPersistentStoreCoordinator = {
    let coordinator: NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let applicationDocumentsDirectory: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
    let persistentStoreUrl: URL = applicationDocumentsDirectory.appendingPathComponent("Model.sqlite")

    do {
        try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: persistentStoreUrl, options: nil)
    }
    catch {
        fatalError("Persistent store error! \(error)")
    }

    return coordinator
}()


lazy var managedObjectContext: NSManagedObjectContext = {
    let managedObjectContext: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = self.peristentStoreCoordinator

    return managedObjectContext
}()


func saveContext() {
    if self.managedObjectContext.hasChanges {
        do {
            try self.managedObjectContext.save()
        }
        catch {
            fatalError("There was an error saving the managed object context \(error)")
        }
    }
}

}

第2步:创建实体 第3步:创建ManagedObjectModelSubclass - 编辑器 - > ManagedObjectModelSubclass 第4步:在类上导入核心数据并添加以下代码

    var person = [Person]() //[Person] here denote subclassclass name
    var  appDelegate = UIApplication.shared.delegate as! AppDelegate

    let personEntity: NSEntityDescription? = NSEntityDescription.entity(forEntityName: "EntityName", in: self.appDelegate.coreDataStack.managedObjectContext)

    if personEntity != nil {

        let person1: Person = Person(entity: personEntity!, insertInto: self.appDelegate.coreDataStack.managedObjectContext)
        person1.name = "name"
        person1.country = "US"
        person1.age = "26"
        person1.place = "NewYork"
     }

步骤5:对于获取数据,请使用以下代码

  var persons: [Person] = [] // subclass name

  var appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate

var listdata = [ModelClass]() // create a modelclass object

  func fetchDemoData() {
    let fetchRequest: NSFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
    do {
        if let results = try self.appDelegate.coreDataStack.managedObjectContext.fetch(fetchRequest) as? [NSManagedObject] {
            let personList: [Person]? = results as? [Person]
            if personList != nil {
                self.persons = personList!


                for eachData in persons {

                    let name = eachData.name as String!
                    let username = eachData.age as String!
                    let email = eachData.country as String!
                    let address = eachData.place as! [String : Any]

                    self.listdata.append(ModelClass(name: name!, username: username!,email : email!,address : address))
                }

                 //self.tableview.reloadData()

            }


        }
    }
    catch {
        fatalError("There was an error fetching the items")
    }
}

答案 1 :(得分:0)

let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
        let newUser = NSManagedObject(entity: entity!, insertInto: context)
        newUser.setValue("Shashikant", forKey: "username")
        newUser.setValue("1234", forKey: "password")
        newUser.setValue(1, forKey: "age")
        do {
            try context.save()
        } catch {
            print("Failed saving")
        }
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
        //request.predicate = NSPredicate(format: "age = %@", "12")
        request.returnsObjectsAsFaults = false
        do {
            let result = try context.fetch(request)
            for data in result as! [NSManagedObject] {
                print(data.value(forKey: "id") as! String)
                print(data.value(forKey: "username") as! String)
            }

        } catch {

            print("Failed")
        }

答案 2 :(得分:0)

导入UIKit

导入CoreData

ViewController类:UIViewController {

@IBOutlet weak var txtName: UITextField!
@IBOutlet weak var txtId: UITextField!
@IBOutlet weak var txtMark: UITextField!
@IBOutlet weak var labelStatus: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

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

@IBAction func buutonSave(_ sender: Any) {
     let appDelegateObject:AppDelegate = UIApplication.shared.delegate as! AppDelegate
     let managedObject:NSManagedObjectContext = appDelegateObject.persistentContainer.viewContext
     let entityDescription =
        NSEntityDescription.entity(forEntityName: "Student",
                                   in: managedObject)
    var student = NSManagedObject(entity: entityDescription!, insertInto: managedObject)
    [student .setValue(self.txtName.text, forKey: "name")]
    [student .setValue(self.txtId.text, forKey: "id")]
    [student .setValue(self.txtMark.text, forKey: "mark")]
     labelStatus.text = "Contact Saved"

}

@IBAction func buttonFind(_ sender: Any) {
    let appDelegateObject:AppDelegate = UIApplication.shared.delegate as! AppDelegate
    let managedObject:NSManagedObjectContext = appDelegateObject.persistentContainer.viewContext
    let entityDescription =
        NSEntityDescription.entity(forEntityName: "Student",
                                   in: managedObject)

    let request = NSFetchRequest<NSFetchRequestResult>()
    request.entity = entityDescription

    let pred = NSPredicate(format: "(name = %@)", txtName.text!)
    request.predicate = pred
    do {
        var results =
            try managedObject.fetch(request)

        if results.count > 0 {
            let match = results[0] as! NSManagedObject

            txtName.text = match.value(forKey: "name") as? String
            txtId.text = match.value(forKey: "id") as? String
            txtMark.text = match.value(forKey: "mark") as? String
            labelStatus.text = "Matches found: \(results.count)"
        } else {
            labelStatus.text = "No Match"
        }

    } catch let error as NSError {
        labelStatus.text = error.localizedFailureReason
    }
}

}

答案 3 :(得分:0)

//CoreDataRose
ad = (UIApplication.shared.delegate as! AppDelegate) moc = ad.persistentContainer.viewContext
actorEntity = NSEntityDescription.entity(forEntityName: "Actors", in: moc)
func fetch() {

        let fetchReq = NSFetchRequest<NSFetchRequestResult>(entityName: "Actors")

        do{
            let actorsArr = try moc.fetch(fetchReq)

            for i in 0..<actorsArr.count
            {
                let mo:NSObject = actorsArr[i] as! NSManagedObject
                print(mo.value(forKey: "empFName")!)     
                DispatchQueue.main.async {
                    actorsArray.append(actors(firstName: (mo.value(forKey: "empFName") as? String), lastName: (mo.value(forKey: "empLName") as? String ), age: (mo.value(forKey: "empAge") as? Int)))
                }
            }
        }catch{
            print("Error Message")
        }    
    }
@IBAction func submitBtn(_ sender: Any) {

//        var secondView = storyboard?.instantiateViewController(withIdentifier: "DisplayView") as! DisplayView
//        secondView.firstView = self
//        present(secondView, animated: true)

        actorsArray.append(actors(firstName: "\(firstNameTF.text!)", lastName: "\(lastNameTF.text!)",  age: ageTF.text! as? Int))

        var mo2 = NSManagedObject(entity: actorEntity, insertInto: moc)

        mo2.setValue(firstNameTF.text, forKey: "empFName")
        mo2.setValue(lastNameTF.text, forKey: "empLName")
        mo2.setValue(Int(ageTF.text!), forKey: "empAge")

        do{
            try moc.save()
        }catch{
            print("Error")
        }  
    }
@IBAction func chooseImageButton(_ sender: Any) {

        let image = UIImagePickerController()

        image.delegate = self

        image.sourceType = UIImagePickerController.SourceType.photoLibrary

        image.allowsEditing = false
        self.present(image, animated: true)
        {

        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
        {
            importImage.image = image
        }
        else{
            print("error message")
        }

        self.dismiss(animated: true, completion: nil)
    }