Last active
March 17, 2023 19:29
-
-
Save kristopherjohnson/6f14a50006127424faf3 to your computer and use it in GitHub Desktop.
Swift utility function to create and reuse a thread-local object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
/// Return a thread-local object, creating it if it has not already been created | |
/// | |
/// :param: create closure that will be invoked to create the object | |
/// :returns: object of type T | |
public func cachedThreadLocalObjectWithKey<T: AnyObject>(key: String, create: () -> T) -> T { | |
if let threadDictionary = NSThread.currentThread().threadDictionary { | |
if let cachedObject = threadDictionary[key] as T? { | |
return cachedObject | |
} | |
else { | |
let newObject = create() | |
threadDictionary[key] = newObject | |
return newObject | |
} | |
} | |
else { | |
assert(false, "threadDictionary should never be nil") | |
// If we don't have a thread-local dictionary for some reason, | |
// then just call create() on every call | |
return create() | |
} | |
} | |
// Example | |
/// Get a thread-local date formatter object | |
func getThreadLocalRFC3339DateFormatter() -> NSDateFormatter { | |
return cachedThreadLocalObjectWithKey("net.kristopherjohnson.example.MyThreadLocalDateFormatter") { | |
println("This block will only be executed once") | |
let enUSPOSIXLocale = NSLocale(localeIdentifier: "en_US_POSIX") | |
let rfc3339DateFormatter = NSDateFormatter() | |
rfc3339DateFormatter.locale = enUSPOSIXLocale | |
rfc3339DateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'" | |
rfc3339DateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) | |
return rfc3339DateFormatter | |
} | |
} | |
let x1 = getThreadLocalRFC3339DateFormatter() | |
let x2 = getThreadLocalRFC3339DateFormatter() | |
let x3 = getThreadLocalRFC3339DateFormatter() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment