【发布时间】:2018-08-11 05:49:18
【问题描述】:
我正在尝试使用 Coredata 实现 Codable。我已经尝试遵循以下答案,但仍然没有运气。
How to use swift 4 Codable in Core Data?
我遇到的错误/问题是我的项目继续说:“每当我尝试编码或解码对象时,参数类型‘用户’不符合预期的类型‘可编码’。
我在 CoreData 中创建了实体并创建了 NSManagedObject 子类:
import Foundation
import CoreData
@objc(User)
public class User: NSManagedObject, Codable {
// MARK: - Codable setUp
enum CodingKeys: String, CodingKey {
case fullname
case email
case zipcode
case usertype = "user_type"
}
// MARK: - Decoding the data
required convenience init(from decoder: Decoder) {
guard let context = decoder.userInfo[.context] as? NSManagedObjectContext else {NSLog("Error: with User context!")
return
}
guard let entity = NSEntityDescription.entity(forEntityName: "User", in: context) else {
NSLog("Error with user enity!")
return
}
self.init(entity: entity, in: context)
let values = try decoder.container(keyedBy: CodingKeys.self)
fullname = try values.decode(String.self, forkey: .fullname)
email = try values.decode(String.self, forkey: .email)
zipcode = try values.decode(String.self, forkey: .zipcode)
userType = try values.decode(String.self, forkey: .userType)
}
// MARK: - Encoding the data
func encode(to encoder: Encoder) throws {
var container = try encoder.container(keyedBy: CodingKeys.self)
try container.encode(fullname, forkey: .fullname)
try container.encode(email, forkey: .email)
try container.encode(usertype, forkey: .usertype)
try container.encode(zipcode, forkey: .zipcode)
}
}
// This helps with decoding
extension CodingUserInfoKey {
static let context = CodingUserInfoKey(rawValue: "context")
}
当我尝试解码对象并将用户保存到 firebase 时,我收到一条警告,提示“在参数类型 'User.Type' 中,'User' 不符合预期的类型 'Decodable'
当我尝试编码时,我收到一条警告说“参数类型'用户'不符合预期的类型'可编码'
【问题讨论】:
-
您的代码在操场上给出了不同的错误。它说您的
init和encode方法必须声明为public,因为您的用户类是public。您没有收到这些错误吗?
标签: swift xcode core-data codable