首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >managedObjectContext返回nil

managedObjectContext返回nil
EN

Stack Overflow用户
提问于 2015-10-30 05:48:34
回答 1查看 835关注 0票数 1

我已经创建了一个助手类,它只包含从核心数据和解析中检索数据的方法,DataService.swift

在这个类中,我有以下代码(还有更多):

代码语言:javascript
复制
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)")
        }

    }

但是,这会抛出一个

代码语言:javascript
复制
fatal error: unexpectedly found nil while unwrapping an Optional value

在……上面

代码语言:javascript
复制
let managedContext = appDelegate.managedObjectcontext

下面是managedObjectContext声明:

代码语言:javascript
复制
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
}()

有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2015-10-30 05:53:37

delegate是一个可选变量。我想你只是没有设置一个委派。

代码语言:javascript
复制
unowned(unsafe) var delegate: UIApplicationDelegate?

尝试在使用前检查委派:

代码语言:javascript
复制
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
     // use appDelegate
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33425215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档