ios - Delay between setNeedsDisplay() and call of redraw() function -


i writing app fetches steps data healthkit , displays statistics on screen. have viewcontoller delegate protocol function:

func uservalueforhistogramview(sender: histogramview) -> cgfloat? {         return uservalue     } 

where uservalue is:

var uservalue : cgfloat = 1000 {     didset{         println("didset")         histogramview.setneedsdisplay()     } } 

the drawrect function on histogramview looks this:

override func drawrect(rect: cgrect) {         var value = datasource?.uservalueforhistogramview(self)         println("\(value)")     } 

i initiate update of uservalue through function:

func startrefreshbygettinguservalue() 

when function simply:

func startrefreshbygettinguservalue(){         uservalue = 1500; } 

i instantaneous log message "didset" followed value of uservalue redrawrect().

now, when change function :

func startrefreshbygettinguservalue(){         let calendar = nscalendar.currentcalendar()         let today = nsdate()          let components = calendar.components(.calendarunityear | .calendarunitmonth | .calendarunitday, fromdate: today)          let startdate = calendar.datefromcomponents(components)          let enddate = calendar.datebyaddingunit(.calendarunitday,             value: 1, todate: startdate!, options: nscalendaroptions(0))          let predicate = hkquery.predicateforsampleswithstartdate(startdate, enddate: enddate, options: .strictstartdate)          let samplequery = hkstatisticsquery(quantitytype: hkobjecttype.quantitytypeforidentifier(hkquantitytypeidentifierstepcount), quantitysamplepredicate: predicate, options: .cumulativesum)             { (samplequery, results, error ) -> void in                  if let quantity = results?.sumquantity(){                     self.uservalue = cgfloat(quantity.doublevalueforunit(hkunit.countunit()) )                  }         }         hkstore.executequery(samplequery) } 

i instantaneous "didset" message in log, actual value comes 10 seconds later (i.e. drawrect lagged).

why happen? , how make work without delay ?

apple docs:

queries run on anonymous background queue. query complete, results handler executed on same background queue (but not on same thread). typically dispatch these results main queue update user interface.

the closure passing in completion handler runs asynchronously, uservalue set , setneedsdisplay() called in background. that's not good.

uikit apis should called on main thread.

an easy fix be:

var uservalue : cgfloat = 1000 {     didset{         println("didset")         dispatch_async(dispatch_get_main_queue()) {             histogramview.setneedsdisplay()         }     } } 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -