// // KMNumberArrayFormatter.swift // PDF Reader Pro // // Created by tangchao on 2023/11/10. // import Cocoa class KMNumberArrayFormatter: Formatter { var numberFormatter: NumberFormatter? override init() { super.init() self._commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) self._commonInit() } override func copy(with zone: NSZone? = nil) -> Any { let fm = super.copy(with: zone) as? KMNumberArrayFormatter fm?.numberFormatter = (self.numberFormatter?.copy(with: zone) as! NumberFormatter) return fm as Any } override func string(for obj: Any?) -> String? { var objs: [NSNumber] = [] // if let _ = obj as? String { // objs = [] // } else if let _ = obj as? NSNumber { objs.append(obj as! NSNumber) } var string = "" for number in objs { if let s = self.numberFormatter?.string(for: number), s.isEmpty == false { if string.isEmpty == false { string.append(" ") } string.append(s) } } return string } override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer?) -> Bool { var number: AnyObject? var array: [NSNumber] = [] var success = true for s in string.components(separatedBy: " ") { success = self.numberFormatter?.getObjectValue(&number, for: s, errorDescription: error) ?? false if s.isEmpty == false && success { if let data = number as? NSNumber { array.append(data) } } if success == false { break } } if success { // &obj = array obj?.pointee = array as AnyObject } return success } } extension KMNumberArrayFormatter { private func _commonInit() { self.numberFormatter = NumberFormatter() self.numberFormatter?.formatterBehavior = .behavior10_4 self.numberFormatter?.numberStyle = .decimal self.numberFormatter?.format = "0;0;-0" self.numberFormatter?.minimum = NSNumber(value: 0) } }