Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFetchedResultsController not working with transient property for sectionNameKeyPath

Working fine in Swift 3 with Xcode8.3

I have a 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.

like image 957
D4ttatraya Avatar asked Nov 26 '25 23:11

D4ttatraya


1 Answers

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()
}
like image 129
Doug Avatar answered Nov 29 '25 16:11

Doug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!