xcode - dispatch_after in swift explanation -
i working on project , part of need unhighlight button after set period of time. decided use dispatch_after.
i have managed working, can please explain me how line of code works? have been unable understand how dispatch_after works.
dispatch_after(dispatch_time(dispatch_time_now, int64(1000 * double(nsec_per_msec))), dispatch_get_main_queue()) { self.redbutton.highlighted = false }
let's break down multiple statements:
let when = dispatch_time(dispatch_time_now, int64(1000 * double(nsec_per_msec))) let queue = dispatch_get_main_queue() dispatch_after(when, queue) { self.redbutton.highlighted = false } dispatch_after() enqueues block execution @ time on queue. in case, queue "main queue" "the serial dispatch queue associated application’s main thread". ui elements must modified on main thread only.
the when: parameter of dispatch_after() dispatch_time_t documented "a abstract representation of time". dispatch_time() utility function compute time value. takes initial time, in case dispatch_time_now "indicates time occurs immediately", , adds offset specified in nanoseconds:
let when = dispatch_time(dispatch_time_now, int64(1000 * double(nsec_per_msec))) nsec_per_msec = 1000000 number of nanoseconds per millisecond,
int64(1000 * double(nsec_per_msec)) is offset of 1000*1000000 nanoseconds = 1000 milliseconds = 1 second.
the explicit type conversions necessary because swift not implicitly convert between types. using double ensures works in cases like
let when = dispatch_time(dispatch_time_now, int64(0.3 * double(nsec_per_sec))) to specify offset of 0.3 seconds.
summary: code enqueues block executed on main thread in 1000 ms now.
Comments
Post a Comment