콘텐츠로 건너뛰기
Home » (Swift) tip – NSDateFormatter는 singleton으로 사용하라?

(Swift) tip – NSDateFormatter는 singleton으로 사용하라?

NSDateFormatter와 관련된 애플 공식 문서에는 다음과 같은 내용이 있다.

날짜 포매터를 생성하는 일은 비싼 작업입니다. 만약 포매터를 빈번하게 사용해야한다면, 여러 개의 인스턴스를 만들고 버리는것보다 하나의 인스턴스를 만들어서 이를 캐시에 보관해두는 편이 더 효율적입니다. static 변수를 사용하는 것도 한 가지 방법입니다. 1

이는 포매터에 의존하는 어떤 타입이 있을 때, 싱글턴을 쓰기에 참 좋은 예가 된다는 것을 암시한다. Objective-C에서는 싱글턴을 다음과 같은 식으로 만들었다.

@implementation SomeClass
+(NSDateFormatter*) defaultFormatter{
    static NSDateFormatter *defaultFormatter = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        defaultFormatter= [[NSDateFormatter alloc] init];
    });
    return defaultFormatter;
}

Swift에서는 GCD와 관련한 API에서 dispatch_once에 대응하는 코드를 사용할 필요가 없다. 타입프로퍼티에 대해서 단 한번만 초기화되는 것을 언어차원에서 보장하기 때문이다.

class SomeClass {
    static let defaultFormatter: NSDateFormatter = {
        return NSDateFormatter()
    }
}

  1. “Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. One approach is to use a static variable.”