0

How do we fetch unique Calendar Dates for Core Data Objects?

For example: If we have three emotion objects with NSDates:

"2014-08-04 20:33:42 +0000",
"2014-08-04 20:50:33 +0000",
"2014-08-04 20:50:46 +0000",
"2014-08-06 20:35:58 +0000",
"2014-08-08 20:33:49 +0000"

I want to get an array of NSDates that looks like this:

2014-08-04 
2014-08-06 
2014-08-08

I have explored these threads as possible solutions but neither of them work.

A possibility would be to make time and date attributes for the managed objects I am searching for but that seems like a clunky work around.

Another possibility is to strip the time component of the all the NSDates that come back then filter the array of Dates again for duplicates. Again this seems really clunky and prone to breaking.

I want to get an array of NSDates with only the calendar date and then use that information to present tableview cells. When the user taps a given tableView cell I can push a viewController that displays data related to that calendar date. As time goes on the number of NSDates could get large because there will be many objects with NSDates to search for so the solution should be efficient.

Community
  • 1
  • 1
aaronium112
  • 2,992
  • 4
  • 35
  • 50

1 Answers1

1

You're going to have to use an approach like the ones you describe, because that's how it needs to be done.

You're storing NSDate values, but NSDate doesn't actually represent a date-- it represents a specific moment in time, to the fraction of a second (it might have been better if it were called something like NSDateTime, but it wasn't). It's really an object wrapper around an NSTimeInterval, which is just a double. Core Data just saves this value, automatically converting to/from NSDate when necessary. As a result, you don't actually have unique calendar dates in your sample data. The time of day is different, which means each of your sample values represents a different double value in the persistent store.

If you want unique date values, you need to either add a field that encodes only the date, or to fetch all of the NSDate style attributes and filter the result. I'd probably go with the first-- store the data you actually need to look up-- but either will work.

Tom Harrington
  • 69,312
  • 10
  • 146
  • 170