我试图在我的主应用程序中使用CoreData,我想通过Today Extension以及以后在WatchApp中访问它。
我为“今日”小部件添加了一个新目标-这两个目标均已激活了AppGroup。当然是相同的appGroup。
然后,我建立了一个“SharedCode”框架。要在Main和Today应用程序中共享帮助程序类和CoreDataStack类。
我构建了此博客文章中提到的CoreDataStack:https://swifting.io/blog/2016/09/25/25-core-data-in-ios10-nspersistentcontainer/
我还添加了此代码,以更改目录:
final class PersistentContainer: NSPersistentContainer {
internal override class func defaultDirectoryURL() -> URL {
var url = super.defaultDirectoryURL()
if let newURL =
FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: CoreDataServiceConsts.applicationGroupIdentifier) {
url = newURL
}
return url
}
}
这是我的CoreDataStack Helper类:
struct CoreDataServiceConsts {
static let applicationGroupIdentifier = "nnnnnnnnn.group.is.xnd.xyz"
static let modelName = "Weight"
}
public class CoreDataStack {
public static let shared = CoreDataStack()
public var errorHandler: (Error) -> Void = {_ in }
//#1
public lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: CoreDataServiceConsts.modelName)
container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in
if let error = error {
NSLog("CoreData error \(error), \(error._userInfo)")
self?.errorHandler(error)
}
})
return container
}()
//#2
public lazy var viewContext: NSManagedObjectContext = {
return self.persistentContainer.viewContext
}()
//#3
// Optional
public lazy var backgroundContext: NSManagedObjectContext = {
return self.persistentContainer.newBackgroundContext()
}()
//#4
public func performForegroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
self.viewContext.perform {
block(self.viewContext)
}
}
//#5
public func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
self.persistentContainer.performBackgroundTask(block)
}
public func saveContext () {
guard viewContext.hasChanges else { return }
do {
try viewContext.save()
} catch let error as NSError {
print("Unresolved error \(error), \(error.userInfo)")
}
}
}
我为NSPersistentContainer建立了一个子类:
final class PersistentContainer: NSPersistentContainer {
internal override class func defaultDirectoryURL() -> URL {
var url = super.defaultDirectoryURL()
if let newURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: CoreDataServiceConsts.applicationGroupIdentifier) {
url = newURL
}
return url
}
}
在我的主应用程序中,我使用NSFetchedResultController-添加和获取Entity可以正常工作:)
现在我想从CoreData中读取-我使用了FetchRequest:
func fetchWeights() {
let fetchRequest: NSFetchRequest<Measure> = Measure.fetchRequest()
let dateSort = NSSortDescriptor(key: #keyPath(Measure.date), ascending: false)
fetchRequest.sortDescriptors = [dateSort]
fetchRequest.returnsObjectsAsFaults = false
do {
let results = try CoreDataStack.shared.viewContext.fetch(fetchRequest)
if results.count > 0 {
// There are found Weigts
print("weights FOUND: \(results.count)")
} else {
// Nil Weights found
print("NO weights: \(results.count)")
}
} catch let error as NSError {
print("Fetch error: \(error) description: \(error.userInfo)")
}
}
没有提取请求总是返回零个对象。
但是我的CoreData中有实体-我的主应用程序中有实体。
有任何想法吗?
我不知道我在做什么错..
谢谢你的帮助。
最佳答案
您已经定义了PersistentContainer
子类来覆盖defaultDirectoryURL
,但是您的CoreDataStack
仍在为惰性容器使用NSPersistentContainer
中的内置类型。
这应该可以解决问题:
public class CoreDataStack {
public static let shared = CoreDataStack()
public var errorHandler: (Error) -> Void = {_ in }
//#1
public lazy var persistentContainer: PersistentContainer = {
let container = PersistentContainer(name: CoreDataServiceConsts.modelName)
container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in
if let error = error {
NSLog("CoreData error \(error), \(error._userInfo)")
self?.errorHandler(error)
}
})
return container
}()
干杯
Michał