【问题标题】:NSFetchedResultsController fetchedObjects returning nilNSFetchedResultsController fetchedObjects 返回 nil
【发布时间】:2017-04-23 09:41:47
【问题描述】:

我使用下面的代码从核心数据中获取Article 的列表,它给了我预期的结果。

    let moc = CoreDataHelper().backgroundContext
    let employeesFetch = NSFetchRequest<NSFetchRequestResult>(entityName:"Article")
    do {
    let fetchedEmployees = try moc?.fetch(employeesFetch) as! [Article]
    print(fetchedEmployees.count)
    } catch {
    fatalError("Failed to fetch employees: \(error)")
    }

输出:376

但是当我尝试使用 NSFetchedResultsController 进行获取时。 fetchedObjects 总是返回 nil。我使用了下面的代码。

 fileprivate lazy var fetchedResultsController: NSFetchedResultsController<Article> = {
        // Create Fetch Request
        let moc = CoreDataHelper().backgroundContext
       // let fetchRequest: NSFetchRequest<Article> = Article.fetchRequest()
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"Article")
        // Configure Fetch Request
        fetchRequest.sortDescriptors = [NSSortDescriptor(key:"category", ascending: true)]
        // Create Fetched Results Controller
        let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:moc!, sectionNameKeyPath: nil, cacheName: nil)
        // Configure Fetched Results Controller
        fetchedResultsController.delegate = self
        let quotes = fetchedResultsController.fetchedObjects
        return fetchedResultsController as! NSFetchedResultsController<Article>
    }() 

quotes 始终为零。我无法弄清楚是什么问题?

【问题讨论】:

  • 您需要performFetch。见apple doc
  • 不相关,但为什么您使用子类创建未指定的获取请求?如果你写let employeesFetch = NSFetchRequest&lt;Article&gt;(entityName:"Article"),你可以省略fetch 行中的类型转换。这就是泛型类型的好处。

标签: ios core-data swift3 nsfetchedresultscontroller


【解决方案1】:

尝试在闭包外调用 fetchedResultsController 上的 performFetch()。

希望这会奏效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多