Skip to content

Instantly share code, notes, and snippets.

@justinHowlett
Created July 8, 2014 04:37
Show Gist options
  • Save justinHowlett/2d59a3bbf0a7d592d0db to your computer and use it in GitHub Desktop.
Save justinHowlett/2d59a3bbf0a7d592d0db to your computer and use it in GitHub Desktop.
Example of a lazy loaded synchronous background threaded singleton getter in Swift
let kGlobalDateFormatterSharedInstance = GlobalDateFormatterModel()
class GlobalDateFormatterModel: NSObject {
@lazy var defaultDomainDateFormatter: NSDateFormatter = self.initializeDefaultDomainDateFormatter()
class var sharedInstance:GlobalDateFormatterModel {
return kGlobalDateFormatterSharedInstance
}
func initializeDefaultDomainDateFormatter() -> NSDateFormatter{
var semaphoreDone: dispatch_semaphore_t = dispatch_semaphore_create(0);
var formatter: NSDateFormatter?
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
formatter = NSDateFormatter()
if let unwrappedFormatter = formatter{
unwrappedFormatter.dateFormat = kDomainDefaultDateFormatterStyle
unwrappedFormatter.timeZone = NSTimeZone(name: "GMT")
}
dispatch_semaphore_signal(semaphoreDone)
})
dispatch_semaphore_wait(semaphoreDone, DISPATCH_TIME_FOREVER);
return formatter!
}
}
@justinHowlett
Copy link
Author

Ridiculously over engineered? You betcha

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment