我想使用Core数据在今天的扩展程序中显示照片。但是,实体是空的。我对此一无所知。
这就是我正在做的事情:
创建CoreDataStack类,以便在今天的扩展中使用Core数据。
class CoreDataStack {
private init() {
NotificationCenter.default.addObserver(self,
selector: #selector(mainContextChanged(notification:)),
name: .NSManagedObjectContextDidSave,
object: self.managedObjectContext)
NotificationCenter.default.addObserver(self,
selector: #selector(bgContextChanged(notification:)),
name: .NSManagedObjectContextDidSave,
object: self.backgroundManagedObjectContext)
}
static let sharedStack = CoreDataStack()
var errorHandler: (Error) -> Void = {_ in }
@available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "name")
container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in
if let error = error {
NSLog("CoreData error \(error), \(error._userInfo)")
self?.errorHandler(error)
}
})
return container }()
@available(iOS 10.0, *)
lazy var viewContext: NSManagedObjectContext = {
return self.persistentContainer.viewContext
}()
@available(iOS 10.0, *)
func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
self.persistentContainer.performBackgroundTask(block)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
lazy var libraryDirectory: URL = {
let urls = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group...")
return urls!
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: "name", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel:
self.managedObjectModel)
let directory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.kr....")
let urls = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.kr....")!.path
let url = directory!.appendingPathComponent("name.sqlite")
do {
try coordinator.addPersistentStore(ofType:
NSSQLiteStoreType,
configurationName: nil,
at: url,
options: nil)
} catch {
// Report any error we got.
NSLog("CoreData error \(error), \(error._userInfo)")
self.errorHandler(error)
}
return coordinator }()
lazy var backgroundManagedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateManagedObjectContext.persistentStoreCoordinator = coordinator
return privateManagedObjectContext }()
@available(iOS 9.0, *)
lazy var managedObjectContext: NSManagedObjectContext = {
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
return managedObjectContext }()
@objc func mainContextChanged(notification: NSNotification) {
backgroundManagedObjectContext.perform { [unowned self] in
self.backgroundManagedObjectContext.mergeChanges(fromContextDidSave: notification as Notification)
}
}
@objc func bgContextChanged(notification: NSNotification) {
managedObjectContext.perform{ [unowned self] in
self.managedObjectContext.mergeChanges(fromContextDidSave: notification as Notification)
}
}
func saveContext () {
if #available(iOS 10.0, *) {
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)")
}
}
} else {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() 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
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
在今天的扩展视图控制器中添加功能
func fetchData() {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Quotes")
if #available(iOS 10.0,*) {
let context = CoreDataStack.sharedStack.viewContext
do {
let results = try context.fetch(fetchRequest)
self.quotes = results as? [Quotes]
print("result = \(results)")
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
return
}
}else {
//for ios 9.3~
let context = CoreDataStack.sharedStack.managedObjectContext
do {
let results = try context.fetch(fetchRequest)
self.quotes = results as? [Quotes]
print("result = \(results)")
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
return
}
}
for i in self.quotes! {
let image = UIImage(data: i.img! as Data, scale: 1.0)
self.quotesImgs.append(image!)
print("is that really image? \(image)")
print("app in for in sytax for coredata = \(self.quotesImgs)")
}
print("quotes \(self.quotes)")
}
打印为result = [] / quotes Optional([])
我错过了什么?