我已经创建了一个助手类,它只包含从核心数据和解析中检索数据的方法,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
}()有什么想法吗?
发布于 2015-10-30 05:53:37
delegate是一个可选变量。我想你只是没有设置一个委派。
unowned(unsafe) var delegate: UIApplicationDelegate?尝试在使用前检查委派:
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
// use appDelegate
}https://stackoverflow.com/questions/33425215
复制相似问题