我需要一个包含Core Data的数组吗?

时间:2018-01-01 04:06:34

标签: ios core-data swift4

要删除,检索和计算项目,我似乎需要一个数组来标记Core Data。 TableView函数就是一个很好的例子。您需要提供count个项目。 TableView提供indexPath.row来删除和检索项目。

如果没有必须与Core Data保持同步的附带数组,您如何执行上述操作?

为了实现这一点,我可以将Core Data抽象为一个类,并使用它隐藏类中的数组。

2 个答案:

答案 0 :(得分:1)

  

"为了实现这一点,我可以将Core Data抽象为一个类并隐藏它   使用它"

在类中的数组

我发现创建一个数据协调员'应用程序中的单例在应用程序中的任何位置使用相同的数据,为此单例提供了NSManagedObject的数组,这是一种通过许多vc传递动态数据的强大方式,而不通过它SEGUE。

/**
**NSObject Singleton**

Coordinates data between CoreData, real-time database and ViewControllers.

- Eliminates the need to pass data from VC to VC.
- Reduces State Changes when manipulating user data
- Provides a common resource for scaling additional VC without passing data.
- Manages a single NSManagedObject by value
*/
final class DataCoordinator: NSObject {

private override init() {
    print("Data Coordinator Initialized")
}

static let sharedInstance = DataCoordinator()


var fetched: [YourNSManagedObjectModel] = []

//...

拥有一个"数据库控制器"相当普遍。预先形成您的核心数据操作:

class DatabaseController {

private init() {

}

class func getContext () -> NSManagedObjectContext {
    return DatabaseController.persistentContainer.viewContext
}


static var persistentContainer: NSPersistentContainer = {
    //The container that holds both data model entities
    let container = NSPersistentContainer(name: <# NSManagedObjectClass #> )

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */

            //TODO: - Add Error Handling for Core Data

            fatalError("Unresolved error \(error), \(error.userInfo)")
           }


         })
        return container
     }()

class func fetchAll () -> Array<YourNSManagedObjectModel> {
    let all = NSFetchRequest<YourNSManagedObjectModel>(entityName: "YourNSManagedObjectModel")

    var fetchedall:[YourNSManagedObjectModel] = []
    do {
        let fetched = try DatabaseController.getContext().fetch(all)
        fetchedall = fetched

    } catch {
        let nserror = error as NSError
        print(nserror.localizedDescription)
    }
    print("Fetched: \(fetchedall.count) Entites")

    return fetchedall
}

因此,您可以将您的DataCoodinator单例设置为:

DataCoordinator.sharedInstance.fetched = DatabaseController.fetchAll()

然后在任何vc中使用像普通数组一样获取。

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return DataCoordinator.sharedInstance.fetched.count 
 }

完成更新/编辑后,您可以使用简单的功能来保存核心数据上下文。

 DatabaseController.saveContext()


// MARK: - Core Data Saving support
class func saveContext() {
    let context = self.getContext()
    if context.hasChanges {
        do {
            try context.save()
            print("Data Saved to Context")
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. 
            //You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

并删除:

    DatabaseController.getContext().delete(fetched[index])

答案 1 :(得分:1)

  

我需要一个包含Core Data的数组吗?

  

TableView函数就是一个很好的例子。您需要提供[('', ''), ('', '2')] 个项目。

数组只是众多可能的可数数据集合之一。

  

如果没有必须与Core Data保持同步的附带数组,您如何执行上述操作?

您可以使用托管对象上下文。例如,有一个名为-\[NSManagedObjectContext countForFetchRequest:error:\](或在Swift中,count(for:))的方法,它告诉您给定获取请求将返回给定实体的实例数。或者,更常见的情况是,如果您已经拥有与您感兴趣的实体有多对多关系的对象,则可以访问该属性。例如,如果您想在count中填写艺术家的表格,您可能会说recordCollection

你肯定尝试让一个单独的阵列与你的核心数据存储同步 - 你要做很多工作来复制你的核心数据存储已经存储的信息包含,并试图保持两个独立的数据集同步总是容易出错。