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

问题描述 投票:0回答:2

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

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

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

ios core-data swift4
2个回答
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 
 }

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

 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
投票

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

没有。

TableView函数就是一个很好的例子。你需要提供count的物品。

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

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

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

你绝对不应该试图让一个单独的数组与你的核心数据存储保持同步 - 你要做很多工作来复制你的核心数据存储已经包含的信息,并试图保留两组不同的数据。同步总是容易出错。

© www.soinside.com 2019 - 2024. All rights reserved.