OSDN Git Service

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