NSFetchedResultsController not working with transient properties

你说的曾经没有我的故事 提交于 2019-12-12 12:50:59

问题


Working fine in Swift 3 with Xcode8.3

I have an project ongoing which has core data for saving messages.
It sorts messages according to time and sections them according to day.

Here's how:

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)")
}

Here is transient property:

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()
}

Using it as:

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

It always gives 0 sections and sectionTitle property never getting called.

This setup was/is working correctly with Swift3 in Xcode8.3.
Even this is working with Swift3.2 in Xcode9-beta.
But if I switch to Swift4 in Xcode9-beta, it's not working.


回答1:


Add @objc to the transient property, so:

@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:


I just switched 'Swift 3 @objc inference' in the build settings to 'on' and all works fine again.



来源:https://stackoverflow.com/questions/44804683/nsfetchedresultscontroller-not-working-with-transient-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!