“为了实现这一点,我可以将核心数据抽象到一个类中,并隐藏
类中的数组“
我发现在应用程序中创建一个“数据协调器”单例是很常见和方便的,它在应用程序中的任何地方都使用相同的数据,给这个单例一个
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])