【问题标题】:NSFetchedResultsController not working with transient property for sectionNameKeyPathNSFetchedResultsController 不适用于 sectionNameKeyPath 的瞬态属性
【发布时间】:2017-06-28 14:00:06
【问题描述】:

在带有 Xcode8.3 的 Swift 3 中运行良好

我有一个正在进行的项目,其中包含用于保存消息的核心数据。
它根据时间对消息进行排序,并根据日期对它们进行分段。

方法如下:

let request = NSFetchRequest(entityName: "Message")
let sortDiscriptor = NSSortDescriptor(key: "time", ascending: true)
request.sortDescriptors = [sortDiscriptor]

fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: mainThreadMOC, sectionNameKeyPath: "sectionTitle", cacheName: nil)
fetchedResultsController.delegate = self
do {
    try fetchedResultsController.performFetch()
} catch {
    fatalError("Failed to initialize FetchedResultsController: \(error)")
}

这里是瞬态属性:

var sectionTitle: String? {
    //this is **transient** property
    //to set it as transient, check mark the box with same name in data model
    return time!.getTimeStrWithDayPrecision()
}

将其用作:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  let sectionInfo = fetchedResultsController.sections![section]
  let n =  sectionInfo.numberOfObjects
  return n
}

它总是给出 0 个部分并且永远不会调用 sectionTitle 属性。

此设置在 Xcode8.3 中与 Swift3 一起正常工作。
即使这也适用于 Xcode9-beta 中的 Swift3.2。
但是如果我在 Xcode9-beta 中切换到 Swift4,它就不起作用了。

【问题讨论】:

  • 向 Apple 报告错误。
  • 不要使用瞬态作为 sectionNameKeyPath,因为所有对象都会出错,只是为了找出它们所在的部分。而是使用持久属性并为部分实现 tableView 标题。

标签: ios core-data nsfetchedresultscontroller swift4


【解决方案1】:

将@objc 添加到瞬态属性,所以:

@objc var sectionTitle: String? {
    //this is **transient** property
    //to set it as transient, check mark the box with same name in data model
    return time!.getTimeStrWithDayPrecision()
}

【讨论】:

    【解决方案2】:

    我刚刚将构建设置中的“Swift 3 @objc inference”切换为“on”,一切正常。

    【讨论】:

      猜你喜欢
      • 2012-05-15
      • 2013-06-01
      • 2023-03-19
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 2011-05-24
      相关资源
      最近更新 更多