I have created a helper class that only contains methods for retrieving data from Core Data and Parse, DataService.swift
Within that class, I have (amongst more of it) the following code:
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)")
}
}
However, this throws a
fatal error: unexpectedly found nil while unwrapping an Optional value
on
let managedContext = appDelegate.managedObjectcontext
Here is managedObjectContext declaration:
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
}()
Any ideas?
delegate
is an optional variable. I expect you just didn't set a delegate.
unowned(unsafe) var delegate: UIApplicationDelegate?
Try to check the delegate before use:
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
// use appDelegate
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.