Skip to main content

Posts

Showing posts with the label Swift

How to Cache NSDateFormatter?

Instantiating NSDateFormatter objects is slow. Most well-written apps that use NSDateFormatter will make efforts to reduce the number unique instances created. Using a static property is sufficient for most cases, but what if you work on a large app where lots of NSDateFormatter objects are needed by a large number of classes. Wouldn’t it be nice if there was an NSCachedDateFormatter that keeps track of what it has instantiated and will return cached objects and only instantiate new ones when necessary? Wouldn’t it be nice if NSCachedDateFormatter was a singleton and could be used app-wide? Here's a sample class that can be used to fulfill this need.

Globals and Swift (Language)

We’re all aware that global variables are bad and that we shouldn’t do globals. Right? Well... Sometimes you need globally available information like user interface idiom or OS version. This information is available from UIDevice and you can grab it from anywhere in your app. Testing Device Idiom and OS Version in Swift if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone { ... } if UIDevice.currentDevice().systemVersion.compare("8.0", options: NSStringCompareOptions.NumericSearch) != NSComparisonResult.OrderedAscending { ... } However, that’s a lot type type and isn’t easy to read either. In Objective-C we could use macros in the pre-compiled header to make application code easier to read and write.