How to subclass NSLocale for tests

I want to unit test some Swift classes which would take Locale as a parameter and then behave in locale-specific way.

It looks like there is no easy way to provide my own locale implementation though. I'd like to avoid swizzling, so I tried to subclass NSLocale, i.e.:

class MyLocale: NSLocale {
   init(myargs: whatever) {
      // initialize here
      super.init(localeIdentifier: "C")
   }
}

but this crashes in runtime:

 -[NSLocale initWithLocaleIdentifier:]: method only defined for abstract class.

So I re-define that initializer:

class MyLocale: NSLocale {
   override init(localeIdentifier string: String) {
      // initialize here
      super.init(localeIdentifier: string) // putting super.init() here doesn't help either
   }
}

but the result is the same: but this crashes in runtime:

 -[NSLocale initWithLocaleIdentifier:]: method only defined for abstract class.

is there any way to properly do what I want without resorting to Objective-C runtime and method swizzling?

  • I think you have to go to objC. NSLocale is just a bridge to Locale.

Add a Comment

Replies

What are you hoping to achieve by subclassing Locale?

Doing this is tricky because there are three levels of nesting here, namely Locale in Swift, NSLocale in Objective-C, and CFLocale in C. Subclassing NSLocale may not do what you want because a lot of framework code calls CFLocale under the covers.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"