KMNumberArrayFormatter.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // KMNumberArrayFormatter.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/11/10.
  6. //
  7. import Cocoa
  8. class KMNumberArrayFormatter: Formatter {
  9. var numberFormatter: NumberFormatter?
  10. override init() {
  11. super.init()
  12. self._commonInit()
  13. }
  14. required init?(coder: NSCoder) {
  15. super.init(coder: coder)
  16. self._commonInit()
  17. }
  18. override func copy(with zone: NSZone? = nil) -> Any {
  19. let fm = super.copy(with: zone) as? KMNumberArrayFormatter
  20. fm?.numberFormatter = (self.numberFormatter?.copy(with: zone) as! NumberFormatter)
  21. return fm as Any
  22. }
  23. override func string(for obj: Any?) -> String? {
  24. var objs: [NSNumber] = []
  25. // if let _ = obj as? String {
  26. // objs = []
  27. // } else
  28. if let _ = obj as? NSNumber {
  29. objs.append(obj as! NSNumber)
  30. }
  31. var string = ""
  32. for number in objs {
  33. if let s = self.numberFormatter?.string(for: number), s.isEmpty == false {
  34. if string.isEmpty == false {
  35. string.append(" ")
  36. }
  37. string.append(s)
  38. }
  39. }
  40. return string
  41. }
  42. override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
  43. var number: AnyObject?
  44. var array: [NSNumber] = []
  45. var success = true
  46. for s in string.components(separatedBy: " ") {
  47. success = self.numberFormatter?.getObjectValue(&number, for: s, errorDescription: error) ?? false
  48. if s.isEmpty == false && success {
  49. if let data = number as? NSNumber {
  50. array.append(data)
  51. }
  52. }
  53. if success == false {
  54. break
  55. }
  56. }
  57. if success {
  58. // &obj = array
  59. obj?.pointee = array as AnyObject
  60. }
  61. return success
  62. }
  63. }
  64. extension KMNumberArrayFormatter {
  65. private func _commonInit() {
  66. self.numberFormatter = NumberFormatter()
  67. self.numberFormatter?.formatterBehavior = .behavior10_4
  68. self.numberFormatter?.numberStyle = .decimal
  69. self.numberFormatter?.format = "0;0;-0"
  70. self.numberFormatter?.minimum = NSNumber(value: 0)
  71. }
  72. }