如何在Swift中使用来自不同viewControllers的多个CoreData实体

时间:2017-02-17 06:40:25

标签: ios swift core-data entity

我想将数据存储到两个viewControllers的两个 CoreData 实体中。

我可以实现这一点,但是来自一个viewController。使用以下代码。

import UIKit
import CoreData
class ViewController: UIViewController {

    override func viewDidLoad()
    {

        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        let context = appDelegate.persistentContainer.viewContext

        let phoneContactRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "PhoneContacts")

        phoneContactRequest.returnsObjectsAsFaults = false

        let emailContactRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "EmailContacts")

        emailContactRequest.returnsObjectsAsFaults = false
        /*
         // Save to database 

         //object one
         let phoneContactsObject = NSEntityDescription.insertNewObject(forEntityName: "PhoneContacts", into: context)

            phoneContactsObject.setValue("John", forKey: "name")
        phoneContactsObject.setValue("8335636532", forKey: "number")

         //object two
        let emailContactObject = NSEntityDescription.insertNewObject(forEntityName: "EmailContacts", into: context)
        emailContactObject.setValue("Peter@gmail.com", forKey: "email")
        emailContactObject.setValue("Peter", forKey: "emailname")
         */


        do{

            // Fetch from PhoneContacts entity
            let phoneContactResults = try context.fetch(phoneContactRequest)

            if phoneContactResults.count > 0
            {
                for phoneContactResult in phoneContactResults as! [NSManagedObject]
                {
                    if let phoneContactName = phoneContactResult.value(forKey: "name")
                    {
                        print(phoneContactName)
                    }
                    if let phoneContactNumber = phoneContactResult.value(forKey: "number")
                    {
                        print(phoneContactNumber)
                    }
                }
            }
            // Fetch from EmailContacts entity
            let emailContactResults = try context.fetch(emailContactRequest)

            if emailContactResults.count > 0
            {
                    for emailContactResult in emailContactResults as! [NSManagedObject]
                    {
                        if let emailContactName = emailContactResult.value(forKey: "emailname")
                        {
                            print(emailContactName)
                        }
                        if let emailContactEmail = emailContactResult.value(forKey: "email")
                        {
                            print(emailContactEmail)
                        }
                    }
                }
        }
        catch
        {            
        }        
    }    
}

如上所述,我有两个 CoreData 实体PhoneContactsEmailContacts。我可以将数据存储到单个viewController的两个实体中。它有效。

现在,我想要的是,如何将数据存储到来自PhoneContacts 1的实体1(viewController)和来自EmailContacts 2的实体2(viewController)?

我应该将managedObjectContext分享给第二个viewController吗?或者接受任何其他更好的解决方案。

我正在使用Xcode 8.2,Swift 3.0

提前致谢。

2 个答案:

答案 0 :(得分:3)

为CoreData操作创建并使用单例类。

例如

class CoreDataHelper: NSObject
{
   static let sharedInstance = CoreDataHelper()

   func appDelegate()->AppDelegate
   {
     return UIApplication.sharedApplication().delegate as! AppDelegate
   }

   func managedObjectContext() -> NSManagedObjectContext
   {
     return self.appDelegate().managedObjectContext
   }
   func fetchPhoneContacts() -> [NSManagedObject]
   {
      // write code to fetch contacts from PhoneContacts entity
   }
   func fetchEmailContacts() -> [NSManagedObject]
   {
      // write code to fetch contacts from EmaliContacts entity
   }
}

来自viewController1

let phoneContatcs = CoreDataHelper.sharedInstance().fetchPhoneContacts()

来自viewController2

let emailContatcs = CoreDataHelper.sharedInstance().fetchEmailContacts()

注意:我知道问题是针对Swift3的。但是我写了这个答案来说明我们如何做到这一点。

答案 1 :(得分:3)

我在两个不同的VC中使用这两个实体时没有看到任何问题。

您需要做的就是在另一个VC中使用以下两行:

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

然后你可以使用:

let emailContactRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "EmailContacts")
emailContactRequest.returnsObjectsAsFaults = false

let emailContactObject = NSEntityDescription.insertNewObject(forEntityName: "EmailContacts", into: context)
emailContactObject.setValue("Peter@gmail.com", forKey: "email")
emailContactObject.setValue("Peter", forKey: "emailname")

然后,您可以保存上下文&amp;使用您现在使用的相同方法来获取刚刚插入数据库的第二个对象。

希望我有意义。

修改

就个人而言,我更愿意像@raki建议的那样简单地创建核心数据管理器单例类。