OSDN Git Service

Doutakuを導入
[kcd/KCD.git] / KCD / JSONMapper.swift
index 462bf38..09e1f5f 100644 (file)
@@ -8,6 +8,7 @@
 
 import Cocoa
 import SwiftyJSON
+import Doutaku
 
 struct MappingConfiguration<T: NSManagedObject> {
     
@@ -51,7 +52,7 @@ extension String {
     // delete api_ prefix.
     func keyByDeletingPrefix() -> String {
         
-        if self.characters.count < 5 { return self }
+        if self.count < 5 { return self }
         
         return String(self[index(startIndex, offsetBy: 4)...])
     }
@@ -84,10 +85,7 @@ extension JSONMapper {
         let old = object.value(forKey: key)
         if !isEqual(old as AnyObject?, validValue) {
             
-            object.notifyChangeValue(forKey: key) {
-                
-                object.setValue(validValue, forKey: key)
-            }
+            object.setValue(validValue, forKey: key)
         }
     }
     
@@ -147,15 +145,23 @@ extension JSONMapper {
         }
     }
     
-    func commit() {
+    private func sortedObjects<T>(_ entity: Entity<T>) -> [T] {
         
         let store = configuration.editorStore
         
-        guard let objects = try? store.objects(of: configuration.entity, sortDescriptors: sortDescriptors) else {
+        guard let objects = try? store.objects(of: configuration.entity) else {
             
-            return Logger.shared.log("Can not get entity named \(configuration.entity.name)")
+            Logger.shared.log("Can not get entity named \(configuration.entity)")
+            return []
         }
         
+        return (objects as NSArray).sortedArray(using: sortDescriptors) as? [T] ?? []
+    }
+    private func commintInContext() {
+        
+        let store = configuration.editorStore
+        let objects = sortedObjects(configuration.entity)
+        
         let list = (data.type == .array ? data.arrayValue : [data])
         list.forEach {
             
@@ -169,12 +175,20 @@ extension JSONMapper {
                 
             } else {
                 
-                fatalError("Can not get entity named \(configuration.entity.name)")
+                fatalError("Can not get entity named \(configuration.entity)")
             }
         }
         
         finishOperating()
-        store.save(errorHandler: store.presentOnMainThread)
+        store.save()
+    }
+    
+    func commit() {
+        
+        configuration.editorStore
+            .sync {
+                self.commintInContext()
+        }
     }
     
     func beginRegister(_ object: ObjectType) {}