OSDN Git Service

洋上補給の補強増設用のショートネームをつけた
[kcd/KCD.git] / KCD / SuppliesView.swift
index 4dbfbed..b29d6fd 100644 (file)
@@ -8,49 +8,53 @@
 
 import Cocoa
 
-fileprivate var pShipStatusContext: Int = 0
+private var pShipStatusContext: Int = 0
 
-class SuppliesView: NSControl {
-    private let observeKeys = ["fuel", "maxFuel", "bull", "maxBull"]
+final class SuppliesView: NSControl {
+    
     private let suppliesCell: SuppliesCell
     
+    private var fuelObservation: NSKeyValueObservation?
+    private var maxFuelObservation: NSKeyValueObservation?
+    private var bullObservation: NSKeyValueObservation?
+    private var maxBullObservation: NSKeyValueObservation?
+
     override init(frame: NSRect) {
+        
         suppliesCell = SuppliesCell()
+        
         super.init(frame: frame)
+        
         self.cell = suppliesCell
     }
+    
     required init?(coder: NSCoder) {
+        
         suppliesCell = SuppliesCell()
+        
         super.init(coder: coder)
+        
         self.cell = suppliesCell
     }
-    deinit {
-        observeKeys.forEach {
-            suppliesCell.shipStatus?.removeObserver(self, forKeyPath: $0)
-        }
-    }
     
-    var shipStatus: Ship? {
-        get {
-            return suppliesCell.shipStatus
-        }
+    
+    @objc var ship: Ship? {
+        
+        get { return suppliesCell.ship }
         set {
-            observeKeys.forEach {
-                suppliesCell.shipStatus?.removeObserver(self, forKeyPath: $0)
-            }
-            suppliesCell.shipStatus = newValue
-            observeKeys.forEach {
-                suppliesCell.shipStatus?.addObserver(self, forKeyPath: $0, context: &pShipStatusContext)
-            }
+            suppliesCell.ship = newValue
+            
+            fuelObservation = suppliesCell.ship?.observe(\Ship.fuel, changeHandler: updateDisplay)
+            maxFuelObservation = suppliesCell.ship?.observe(\Ship.maxFuel, changeHandler: updateDisplay)
+            bullObservation = suppliesCell.ship?.observe(\Ship.bull, changeHandler: updateDisplay)
+            maxBullObservation = suppliesCell.ship?.observe(\Ship.maxBull, changeHandler: updateDisplay)
+
             needsDisplay = true
         }
     }
     
-    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
-        if context == &pShipStatusContext {
-            needsDisplay = true
-            return
-        }
-        super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
+    private func updateDisplay(ship: Ship, _: Any) {
+        
+        needsDisplay = true
     }
 }