D4ttatraya
D4ttatraya

Reputation: 3404

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.

Upvotes: 3

Views: 722

Answers (2)

Doug
Doug

Reputation: 106

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

Upvotes: 4

theCOCOAdile
theCOCOAdile

Reputation: 11

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

Upvotes: 1

Related Questions