无法使用Core Data类解码JSON

时间:2019-08-01 12:28:33

标签: swift

我已经建立了一个称为Station的Core Data实体,该实体具有单个字符串属性“ name”。我已经生成了一个NSManagedObject子类,并将其修改为类似Decodable的

Station + CoreDataProperties.swift

request()->server('HTTP_REFERER')

Station + CoreDataClass.swift

import Foundation
import CoreData

extension Station {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Station> {
        return NSFetchRequest<Station>(entityName: "Station")
    }
    @NSManaged public var name: String?
}

我在JSON文件中具有以下数据 stationData.json

import Foundation
import CoreData

@objc(Station)
public class Station: NSManagedObject, Decodable {
    private enum CodingKeys: String, CodingKey {
        case name
    }
    required convenience public init(from decoder: Decoder) throws {

        guard let codingUserInfoKeyManagedObjectContext = CodingUserInfoKey.managedObjectContext,
            let managedObjectContext = decoder.userInfo[codingUserInfoKeyManagedObjectContext] as? NSManagedObjectContext,
            let entity = NSEntityDescription.entity(forEntityName: "Station", in: managedObjectContext) else {
                throw("error message")
        }

        self.init(entity: entity, insertInto: managedObjectContext)

        let values = try decoder.container(keyedBy: CodingKeys.self)

        self.name = try values.decodeIfPresent(String.self, forKey: .name)
    }
}
public extension CodingUserInfoKey {
    static let managedObjectContext = CodingUserInfoKey(rawValue: "managedObjectContext")
}

我正在尝试使用以下功能(取自Apple教程)来解码先前的JSON文件

Data.swift

[{"name": "Station1"},{"name": "Station2"}]

此函数无法解码错误为import UIKit import SwiftUI import CoreLocation let stationData: [Station] = load("stationData.json") func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T { let data: Data guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else { fatalError("Couldn't find \(filename) in main bundle.") } do { data = try Data(contentsOf: file) } catch { fatalError("Couldn't load \(filename) from main bundle:\n\(error)") } do { let decoder = JSONDecoder() return try decoder.decode(T.self, from: data) } catch { fatalError("the error is \(error)") } } 的JSON

如果我像这样创建测试结构,

Fatal error: the error is error message: file [path to file]/Data.swift, line 33
(lldb)

,而是执行struct StationTest: Decodable { var name: String } ,它将正确解码。为什么原始的Station类在解码时不起作用?不幸的是,错误消息根本没有帮助。

谢谢!

0 个答案:

没有答案