0

I currently am using CoreData for local storage of my model. I have successfully implemented an NSfetchedResultsController to manage the retrieval and presentation of the data in a tableView.

I wish the data to be organized in sections by local day. So each section will be a unique local day. Similar to most chat apps.

I know that I can save a date property in my managedObject in addition to the timestamp and use that as the sectionNameKeyPath, however that will not work when the user changes the timezone on their device. In this case I will have to go back and change every entry in coreData and change the local day entry.

Is there a simpler way to achieve organizing by day taking into account the possibility of the time zone changing?

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Blog")
let blogSort = NSSortDescriptor(key: "dateCreated", ascending: true)
request.sortDescriptors = [blogSort]
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: "localDate", cacheName: nil)

In this example, dateCreated is a timestamp for the date the blog was created and localDate is the actual calendar date.

alionthego
  • 8,508
  • 9
  • 52
  • 125

2 Answers2

1

This is not an answer for your question. But I think this is helpful for you.

let date = Date.init()
let dateFormatter = DateFormatter.init()
dateFormatter.dateStyle = .short
let stringDate = dateFormatter(stringFrom: date)

And then you can save this string as a localDate to the managedObject.

managedObject.localDate = stringDate
Mannopson
  • 2,634
  • 1
  • 16
  • 32
  • I know how to do that. That will always group sections by local date. But if the user then goes to Europe and the timezone on the phone changes, your date string will be the local date of wherever they left from and the sections will not look right. The answer has to be in transient properties on coreData and many examples for objective C and older swift but no current examples. – alionthego May 15 '18 at 05:18
  • I have not tested yet! But I think it’s possible. So, save the `localDate` as a `Date.init()` to the model. And convert this value to the `Calender.current` while retrieving from the model. – Mannopson May 15 '18 at 05:46
1

I would use a calculated property in the Blog class for this. This is how I would approach this

  1. Save the creation date with the same time zone (GMT is easiest), using ISO8601DateFormatter
  2. Add a transient attribute to the Blog entity, say localCreateDate: Date and calculate it by parsing your stored creation date into a Date instance using the local time zone
  3. Use the new localCreateDate in the fetch controller as the sectionNameKeyPath, see this answer or this by Martin R
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52