我创建了一个辅助类,它只包含从Core Data和Parse中检索数据的方法,DataService.swift
在该课程中,我(以及更多)中包含以下代码:
func getUserStoreItems(itemSkuArray: [String]) {
(...)
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Book")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
let bookListNSManagedObject = results as! [NSManagedObject]
for bookNSManagedObject in bookListNSManagedObject {
print("Here is the Core Data \(bookNSManagedObject)")
}
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
然而,这会抛出一个
fatal error: unexpectedly found nil while unwrapping an Optional value
在
let managedContext = appDelegate.managedObjectcontext
这是managedObjectContext声明:
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
有什么想法吗?
答案 0 :(得分:0)
delegate
是一个可选变量。我希望你没有设置代表。
unowned(unsafe) var delegate: UIApplicationDelegate?
尝试在使用前检查代理:
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
// use appDelegate
}