1

Neither class reference nor any tutorial available online say anything about caching anchors between application runs.

I want to query data between app runs so I get all historical HealthKit entries. At first, I thought I'd need to store last query NSDate in NSUserDefaults and on the next app run I'll just hit this value and set it as startDate of HKSampleQuery but after some reading I came onto this cool thing called HKAnchoredObjectQuery which should be handling this caching for me so whenever I hit I'll get only new entries.

Does this class automatically store anchors or it just stores it on app run and when app is terminated everything gets cleared and I'm starting again with HKAnchoredObjectQueryNoAnchor?

Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
cojoj
  • 6,405
  • 4
  • 30
  • 52

2 Answers2

4

Your app must store the HKQueryAnchor itself. HKAnchoredObjectQuery can't cache it across app launches for you - how would HealthKit know that you were performing the same query for the same purpose?

Allan
  • 7,039
  • 1
  • 16
  • 26
0

After doing some experiments in the code it looks like this anchor is a regular Int (<9.0) or HKQueryAnchor (>=9.0) and it holds value only when app is in froeground.
If you (like me) want to keep this value between app runs you'll have to store it manually for example in NSUserDefaults.

I'm still not fully confident that they can keep an eye on this only based on simple Int value... More reliable solution for me is to manually store NSDate of last query execution and based on this query items only from this range of dates.
One additional thing which may be helpful - HKAnchoredObjectQuery automatically sorts returned data in ascending order.

cojoj
  • 6,405
  • 4
  • 30
  • 52
  • It is true that you need to store the anchor some place like NSUserDefaults. It is not true that the results are automatically sorted in date ascending order. They are sorted in anchor order. Try adding a sample to HealthKit from the past and you will see that it is the next object returned by HKAnchoredObjectQuery. – Allan Sep 08 '15 at 22:21
  • Also, dates would not be a reliable way to track changes for this type of query. The integer anchor is a monotonically increasing number that designed to track exactly what your app has seen and what it hasn't regardless of the dates associated with the sample. – Allan Sep 08 '15 at 22:23
  • Well yeah but integer is kinda short... I think `HealthKit` may reach it's limit and what later? – cojoj Sep 09 '15 at 09:05
  • 3
    An integer is large enough. In order for HealthKit to run out of anchors, there would need to be around 4,294,967,296 samples created (that's on 32 bit devices). With that many samples, performance would become a problem much sooner than running out anchors. – Allan Sep 09 '15 at 16:04