使用带有swift3的fetchedResultsController

时间:2016-10-25 05:08:47

标签: ios swift core-data swift3

我想在我的代码中使用fetchedResultsController和Swift3。我试过this way和其他方式,但我无法做到。这是我的代码(它不起作用):

var fetchedResultsController: NSFetchedResultsController<Entity> {

    let fetchRequest: NSFetchRequest<Entity>
    if #available(iOS 10.0, *) {
        fetchRequest = Entity.fetchRequest()
    } else {
        // Fallback on earlier versions
        fetchRequest = NSFetchRequest(entityName: "Entity")
    }

    fetchRequest.fetchBatchSize = 20

    let orderDescriptor = NSSortDescriptor(key: "archiveOrder", ascending: true)
    let nameDesctiptor = NSSortDescriptor(key: "entityName", ascending: false)

    fetchRequest.sortDescriptors = [orderDescriptor, nameDesctiptor]

    let aFetchedResultsController: NSFetchedResultsController<Entity> = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: appDelegate.managedObjectContext, sectionNameKeyPath: nil, cacheName: "Master")
    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController

    do {
        try _FetchedResultsController.performFetch()
    } catch {
        let nserror = error as NSError
        print("Unresolved error \(nserror), \(nserror.userInfo)")
    }

    return _FetchedResultsController!
}

你能给我任何意见或建议吗?

1 个答案:

答案 0 :(得分:0)

Apple基本上建议使用一个只在闭包中运行一次代码的闭包将NSFetchedResultsController声明为非可选的延迟初始化属性。

lazy var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = { ... }()

您的代码无法编译,因为Swift代码区分大小写,这意味着_fetchedResultsController_FetchedResultsController是两个不同的东西。

其余代码似乎是正确的。

lazy var fetchedResultsController: NSFetchedResultsController<Entity> = {

  let fetchRequest: NSFetchRequest<Entity>
  if #available(iOS 10.0, *) {
    fetchRequest = Entity.fetchRequest()
  } else {
    // Fallback on earlier versions
    fetchRequest = NSFetchRequest(entityName: "Entity")
  }
  fetchRequest.fetchBatchSize = 20

  let orderDescriptor = NSSortDescriptor(key: "archiveOrder", ascending: true)
  let nameDesctiptor = NSSortDescriptor(key: "entityName", ascending: false)

  fetchRequest.sortDescriptors = [orderDescriptor, nameDesctiptor]

  let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, 
                                                     managedObjectContext: appDelegate.managedObjectContext, 
                                                       sectionNameKeyPath: nil, 
                                                                cacheName: "Master")
  aFetchedResultsController.delegate = self

  do {
    try aFetchedResultsController.performFetch()
  } catch {
    let nserror = error as NSError
    print("Unresolved error \(nserror), \(nserror.userInfo)")
  }

  return aFetchedResultsController
}()