我有一个iOS应用程序,它使用核心数据存储持久性数据。 当我的Apple Watch伴侣应用启动时,此数据将发送到手表,如果手表中的数据不同,则会更新手表的数据。 SchoolCompanion.xdatamodeld是我的coreData模型,目标都是(iOS应用程序和Watch Extension) 如何在我的iOS应用程序上处理核心数据? 1.我创建了一个phony项目,并将其复制并粘贴到我的appDelegate.swift中 //标记:-核心数据堆栈
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "SchoolCompanion")
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.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} 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)")
}
}
}
我将NSPersistentContainer名称更改为我的项目名称:“ SchoolCompanion”,核心数据模型具有相同的名称(我不知道这是否重要) 1.我创建了一个名为CoreDataHelper.swift的swift文件,以使用我的coreData进行请求获取和其他操作,例如: 导入UIKit 导入CoreData
class CoreDataHelper {
// récupérer base CoreData
private let appDel = UIApplication.shared.delegate as! AppDelegate
// Récupérer le contexte
var context : NSManagedObjectContext {
return appDel.persistentContainer.viewContext
}
// Sauvegarder dans CoreData
func save() {
appDel.saveContext()
}
// ajoute le cours dans coreData
func saveCourse(nom : String, debut: Date, fin: Date, color: Int, prof : String, local : String, day: String) {
let course = Course(context: context)
course.nom = nom
course.heureDebut = debut
course.heureFin = fin
course.strProf = prof
course.strLocal = local
course.color = Int64(color)
course.day = day
save()
print("cours ajouté")
}
// supprime le cours de CoreData
func deleteCourse(cours: Course) {
context.delete(cours)
do {
try context.save()
} catch {
print(error.localizedDescription)
}
}
// renvoie le tableau de tout les cours confondus dans l'odre croissant
var courses : [Course] {
let courseRequest: NSFetchRequest<Course> = Course.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "heureDebut", ascending: true)
courseRequest.sortDescriptors = [sortDescriptor]
var coursestbl : [Course] = []
do {
coursestbl = try context.fetch(courseRequest)
} catch {
print(error.localizedDescription)
}
return coursestbl
}
// renvoie un tableau des cours du lundi
var coursesLun : [Course] {
let courseRequest: NSFetchRequest<Course> = Course.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "heureDebut", ascending: true)
courseRequest.sortDescriptors = [sortDescriptor]
var coursestbl : [Course] = []
do {
coursestbl = try context.fetch(courseRequest)
} catch {
print(error.localizedDescription)
}
var coursLundiTbl : [Course] = []
for c in coursestbl {
if c.day == "LUNDI" {
coursLundiTbl.append(c)
}
}
return coursLundiTbl
}
}
这是我的iOS应用程序,可以正常使用!现在让我们谈谈我的手表应用程序,我做了什么?
我也创建了一个CoreDataHelper:
class CoreDataHelper {
var context : NSManagedObjectContext {
return ExtensionDelegate().persistentContainer.viewContext
}
// Sauvegarder dans CoreData
func save() {
ExtensionDelegate().saveContext()
}
// ajoute le cours dans coreData
func saveCourse(cours : Course) {
let course = Course(context: context)
course.nom = cours.nom
course.heureDebut = cours.heureDebut
course.color = cours.color
course.day = cours.day
//save()
do {
try context.save()
print("context saved successfully")
} catch {
print(error.localizedDescription)
}
}
// ajoute le cours dans coreData
func saveCourse(nom : String, debut: Date, color: Int, day: String) {
let course = Course(context: context)
course.nom = nom
course.heureDebut = debut
course.color = Int64(color)
course.day = day
save()
print("cours ajouté")
}
// supprime le cours de CoreData
func deleteCourse(cours: Course) {
context.delete(cours)
do {
try context.save()
} catch {
print(error.localizedDescription)
}
}
// renvoie le tableau de tout les cours confondus dans l'odre croissant
var courses : [Course] {
get {
let courseRequest: NSFetchRequest<Course> = Course.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "heureDebut", ascending: true)
courseRequest.sortDescriptors = [sortDescriptor]
var coursestbl : [Course] = []
do {
coursestbl = try context.fetch(courseRequest)
} catch {
print(error.localizedDescription)
}
return coursestbl
}
}
}
因此,当手表应用启动时,它将尝试更新coreData的Apple Watch数据,保存成功,但获取请求始终返回空数组。我要扣除coreData在手表上不起作用,但是为什么呢?
也许这可以帮助?
How do I add Core Data stack to WatchKit app