代码之家  ›  专栏  ›  技术社区  ›  4thSpace wkw

我是否需要一个包含核心数据的阵列?

  •  0
  • 4thSpace wkw  · 技术社区  · 8 年前

    要删除、检索和计数项目,似乎需要一个数组来标记核心数据。TableView函数就是一个很好的例子。您需要提供 count 共个项目。TableView提供 indexPath.row 用于删除和检索项目。

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

    为了实现这一点,我可以将核心数据抽象到一个类中,并用它隐藏类中的数组。

    2 回复  |  直到 8 年前
        1
  •  1
  •   RLoniello    8 年前

    “为了实现这一点,我可以将核心数据抽象到一个类中,并隐藏 类中的数组“

    我发现在应用程序中创建一个“数据协调器”单例是很常见和方便的,它在应用程序中的任何地方都使用相同的数据,给这个单例一个 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 singleton设置为:

    DataCoordinator.sharedInstance.fetched = DatabaseController.fetchAll()
    

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

        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])
    
        2
  •  1
  •   Caleb    8 年前

    我是否需要一个包含核心数据的阵列?

    不

    TableView函数就是一个很好的例子。您需要提供 count 共个项目。

    数组只是许多可能的可数数据集合中的一个。

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

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

    你绝对应该 不 尝试保持一个单独的阵列与核心数据存储同步--要复制核心数据存储中已经包含的信息,需要做大量的工作,而尝试保持两组单独的数据同步总是容易出错。