OSDN Git Service

e669ea4856596e57dc887b09af5ab6f316e48e4f
[kcd/KCD.git] / KCD / KCManagedObject.swift
1 //
2 //  KCManagedObject.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/02/02.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Foundation
10 import CoreData
11 import Doutaku
12
13 enum KCManagedObjectError: Error {
14     
15     case invalid
16 }
17
18 class KCManagedObject: NSManagedObject {
19     
20     private static let intValueKyes =
21         [
22     "api_enqflg", "api_aftershipid", "api_progress", "api_usebull",
23     "api_flagship", "api_name_id",
24     "api_comment_id", "api_nickname_id", "api_member_id",
25     "api_flag_0", "api_flag_1", "api_flag_2", "api_flag_3", "api_flag_4",
26     "api_flag_5", "api_flag_6", "api_flag_7",
27     "api_level"
28     ]
29     
30     override func validateValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: String) throws {
31         
32         if value.pointee is NSNull {
33             
34             value.pointee = nil
35             
36             return
37         }
38         
39         if KCManagedObject.intValueKyes.contains(key) {
40             
41             if let _ = value.pointee as? Int {
42                 
43                 return
44             }
45             if let s = value.pointee as? String {
46                 
47                 value.pointee = Int(s) as AnyObject?
48                 
49                 return
50             }
51             
52             print("KCManagedObject type \(type(of: value.pointee))")
53             
54             throw KCManagedObjectError.invalid
55         }
56     }
57     
58     override func value(forUndefinedKey key: String) -> Any? {
59         
60         if key == "description" {
61             
62             return value(forKey: "description_")
63         }
64         
65         if key.hasPrefix("api_") {
66             
67             let k = String(key[key.index(key.startIndex, offsetBy: 4)...])
68             
69             return value(forKey: k)
70         }
71         
72         print("Entity \(String(describing: self)) dose not have key \(key)")
73         
74         return nil
75     }
76     
77     override func setValue(_ value: Any?, forUndefinedKey key: String) {
78         
79         if key == "description" {
80             
81             setValue(value, forKey: "description_")
82             
83             return
84         }
85         
86         if key.hasPrefix("api_") {
87             
88             let k = String(key[key.index(key.startIndex, offsetBy: 4)...])
89             setValue(value, forKey: k)
90             
91             return
92         }
93         
94         print("Entity \(String(describing: self)) dose not have key \(key)")
95     }
96 }