Bazı ilginç birim testlerini gerçekleştirmek için cihazın currentLocale çıkışını değiştirmeye çalışıyorum, bu benim kullandığım koddur, ancak dönen currentLocale'ın yaptığı gibi görünüyor. Devrilme. Herhangi bir ipucu?NSLocale, test amaçları için currentLocale çıkışını değiştirmek için swizzling kullanarak
extension NSLocale {
class func frLocale()->NSLocale{
return NSLocale(localeIdentifier: "fr_FR")
}
class func forceCurrentLocale(){
let originalSelector = #selector(NSLocale.currentLocale)
let swizzledSelector = #selector(self.frLocale)
let originalMethod = class_getClassMethod(self, originalSelector)
let swizzledMethod = class_getClassMethod(self, swizzledSelector)
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
// DÜZENLEME
Yukarıdaki kod çalışmaz. Ben böyle yazarsanız Ama çalışır: bu durumda class_addMethod
nesi
class func forceCurrentLocale(){
let originalSelector = #selector(NSLocale.currentLocale)
let swizzledSelector = #selector(NSLocale.frLocale)
let originalMethod = class_getClassMethod(self, originalSelector)
let swizzledMethod = class_getClassMethod(self, swizzledSelector)
method_exchangeImplementations(originalMethod, swizzledMethod)
}
?