Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Thread-safe date formatter #3

Closed
ghost opened this issue May 23, 2015 · 1 comment
Closed

Thread-safe date formatter #3

ghost opened this issue May 23, 2015 · 1 comment

Comments

@ghost
Copy link

ghost commented May 23, 2015

When handling multiple threads, the shared date formatter can provide a result different than expected due to one thread having a different date_format than another one and being performed at the same time.

@malcommac
Copy link
Owner

I've created a per-thread cache for NSDateFormatter.
It was published with 5d5f25a and available via cocoapods as 1.0.5.
Basically I save and retrive the object from inside the NSThread dictionary; this ensure you to get the instance relative to that thread called only once. It should be enough, tell me if you have problems.

private class func cachedObjectInCurrentThread<T: AnyObject>(key: String, create: () -> T) -> T {
    if let threadDictionary = NSThread.currentThread().threadDictionary as NSMutableDictionary? {
        if let cachedObject = threadDictionary[key] as! T? {
            return cachedObject
        } else {
            let newObject = create()
            threadDictionary[key] = newObject
            return newObject
        }
    } else {
        assert(false, "Current NSThread dictionary is nil. This should never happens, we will return a new instance of the object on each call")
        return create()
    }
}

private class func localThreadDateFormatter() -> NSDateFormatter {
    return NSDate.cachedObjectInCurrentThread("com.library.swiftdate.dateformatter") {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        return dateFormatter
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant