核心数据-[Decodable.Address initWithCoder:]:发送到实例的无法识别的选择器
Posted
技术标签:
【中文标题】核心数据-[Decodable.Address initWithCoder:]:发送到实例的无法识别的选择器【英文标题】:Core data -[Decodable.Address initWithCoder:]: unrecognised selector sent to instance 【发布时间】:2018-06-14 06:30:06 【问题描述】:我已经用 swift Codable 实现了 JSON 解析并用 Coredata 存储它。我的代码在存储 JSON 和获取没有“可转换”属性的实体时工作正常。但是如果它的任何属性是可转换的,那么获取实体会失败并崩溃并显示以下日志。如果是自定义对象,我需要保留可转换属性。看看下面的核心数据模型类并为我的实现获取请求。 控制台日志:
-[Decodable.Address initWithCoder:]: unrecognized selector sent to
instance 0x600000464c40
2018-06-14 11:26:52.768499+0530 Decodable[7870:2988621] [error] error:
exception handling request: <NSSQLFetchRequestContext: 0x600000381fb0>
, -[Decodable.Address initWithCoder:]: unrecognized selector sent to
instance 0x600000464c40 with userInfo of (null)
CoreData: error: exception handling request:
<NSSQLFetchRequestContext: 0x600000381fb0> , -[Decodable.Address
initWithCoder:]: unrecognized selector sent to instance 0x600000464c40
with userInfo of (null)
2018-06-14 11:26:52.777634+0530 Decodable[7870:2988621] ***
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[Decodable.Address
initWithCoder:]: unrecognized selector sent to instance
0x600000464c40'
ViewController.swift
let request = NSFetchRequest<Clinic>(entityName: "Clinic")
request.returnsObjectsAsFaults = true
do
managedObjectContext = appDelegate.persistentContainer.viewContext
let result = try managedObjectContext.fetch(request)//***Crashes!!
catch
print("no record found")
诊所+CoreDataClass.swift
import Foundation
import CoreData
public class Clinic: NSManagedObject, NSCoding
public func encode(with aCoder: NSCoder)
aCoder.encode(address, forKey: ClinicCodingKeys.address.rawValue)
// also encode other class attributes
public required convenience init?(coder aDecoder: NSCoder)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
guard let contextUserInfoKey = CodingUserInfoKey.context,
let managedObjectContext =
appDelegate.persistentContainer.viewContext as?
NSManagedObjectContext,
let entityDescription =
NSEntityDescription.entity(forEntityName:"Clinic", in:
managedObjectContext) else fatalError()
self.init(entity: entityDescription, insertInto:
appDelegate.persistentContainer.viewContext)
self.address = aDecoder.decodeObject(forKey:
ClinicCodingKeys.address.rawValue) as? Address
//*** Also decode other attributes
public override func encode(to encoder: Encoder) throws
var container = encoder.container(keyedBy: ClinicCodingKeys.self)
try container.encode(remoteid , forKey: .remoteid)
try container.encode(landline ?? "" , forKey: .landline)
try container.encode(name ?? "", forKey: .name)
try container.encode(address , forKey: .address)
try container.encode(mobile ?? "", forKey: .mobile)
try container.encode(email ?? "", forKey: .email)
public required convenience init(from decoder: Decoder) throws
guard let contextUserInfoKey = CodingUserInfoKey.context,
let managedObjectContext =
decoder.userInfo[contextUserInfoKey] as? NSManagedObjectContext,
let entity =
NSEntityDescription.entity(forEntityName:"Clinic", in:
managedObjectContext) else fatalError()
self.init(entity: entity, insertInto: managedObjectContext)
let values = try decoder.container(keyedBy: ClinicCodingKeys.self)
remoteid = try values.decode(Int16.self, forKey: .remoteid)
landline = try values.decode(String.self, forKey: .landline)
name = try values.decode(String.self, forKey: .name)
address = try values.decode(Address.self, forKey: .address)
mobile = try values.decode(String.self, forKey: .mobile)
email = try values.decode(String.self, forKey: .email)
诊所+CoreDataProperties.swift
import Foundation
import CoreData
extension Clinic: Codable
@nonobjc public class func fetchRequest() -> NSFetchRequest<Clinic>
return NSFetchRequest<Clinic>(entityName: "Clinic")
@NSManaged public var remoteid: Int16
@NSManaged public var landline: String?
@NSManaged public var name: String?
@NSManaged public var address: Address?//***** Transformable attribute
//for core data model class Address
@NSManaged public var mobile: String?
@NSManaged public var email: String?
enum ClinicCodingKeys: String, CodingKey
case remoteid = "_id"
case landline
case name
case address
case mobile
case email
地址+CoreDataClass.swift
import Foundation
import CoreData
public class Address: NSManagedObject
public func encode(to encoder: Encoder) throws
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(address ?? "" , forKey: .address)
try container.encode(area ?? "" , forKey: .area)
try container.encode(postalcode ?? "" , forKey: .postalcode)
try container.encode(city ?? "" , forKey: .city)
try container.encode(state ?? "" , forKey: .state)
try container.encode(country ?? "" , forKey: .country)
try container.encode(lat ?? "" , forKey: .lat)
try container.encode(lng ?? "" , forKey: .lng)
public required convenience init(from decoder: Decoder) throws
guard let contextUserInfoKey = CodingUserInfoKey.context,
let managedObjectContext =
decoder.userInfo[contextUserInfoKey] as? NSManagedObjectContext,
let entity =
NSEntityDescription.entity(forEntityName:"Address", in:
managedObjectContext) else fatalError()
self.init(entity: entity, insertInto: managedObjectContext)
let values = try decoder.container(keyedBy: CodingKeys.self)
address = try values.decode(String.self, forKey: .address)
area = try values.decode(String.self, forKey: .area)
postalcode = try values.decode(String.self, forKey: .postalcode)
city = try values.decode(String.self, forKey: .city)
state = try values.decode(String.self, forKey: .state)
country = try values.decode(String.self, forKey: .country)
lat = try values.decode(String.self, forKey: .lat)
lng = try values.decode(String.self, forKey: .lng)
地址+CoreDataProperties.swift
import Foundation
import CoreData
extension Address : Codable
@nonobjc public class func fetchRequest() -> NSFetchRequest<Address>
return NSFetchRequest<Address>(entityName: "Address")
@NSManaged public var address: String?
@NSManaged public var area: String?
@NSManaged public var postalcode: String?
@NSManaged public var city: String?
@NSManaged public var state: String?
@NSManaged public var country: String?
@NSManaged public var lat: String?
@NSManaged public var lng: String?
enum CodingKeys: String, CodingKey
case address
case area
case postalcode = "postal_code"
case city
case state
case country
case lat
case lng
我尝试在 Clinic+CoreDataClass.swift 中实现 initWithCoder: 但它给出了错误 - 无法调用 initWith(entity: insertInto:)。我需要实现 initwith(entity: insertinto:)
【问题讨论】:
你也可以发布地址的实现吗? @RohanBhale 添加了 Model 类“Address”的代码。 这里也实现了 NSCoding 协议。这些无法识别的选择器错误属于 NSCoding 协议的缺失方法 但是 Codable 是我们替换旧的 NSCoding 所得到的(检查 [medium.com/if-let-swift-programming/…)。我已经实现了 Codable 。那么为什么需要 NSCoding 协议。当模型类/实体中没有可转换的属性时,同样的实现可以正常工作。那里没有实现 NSCoding 协议。但是当自定义对象作为属性类型传递时(这里是 Clinic+CoreDataProperties.swift 中的“地址”),它会崩溃。 Codable 是 Swift 定义的东西。 CoreData 是使用 objc 运行时开发的。 Codable 可以很好地解析东西。为了保存数据,您需要使用 NSCoding 协议。如果您仔细观察,甚至编码和解码的方法定义都不同 【参考方案1】:您错误地获取它NSFetchRequest<Clinic>(entityName: "Clinic")
,并且在保存到结果变量之前您没有检查实体记录。
let request = NSFetchRequest<Clinic>(entityName: "Clinic")
request.returnsObjectsAsFaults = true
do
managedObjectContext = appDelegate.persistentContainer.viewContext
let result = try managedObjectContext.fetch(request)//***Crashes!!
catch
print("no record found")
将您的代码替换为fetchData()
函数并确保实体名称相同。
func fetchData()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Clinic")
do
let records = try context.fetch(fetchRequest)
if let records = records as? [NSManagedObject]
if !records.isEmpty
var result:[NSManagedObject] = records
print("coreData result : \(records)")
else
print("No record in Clinic entity")
catch
print("Error")
【讨论】:
用你的“fetch”代码替换后,仍然在同一行 context.fetch(fetchRequest) 上使用相同的日志崩溃。 见问题顶部。我得到的日志与我提出的问题相同。 @Shirish 确保诊所是实体名称并将数据正确保存在核心数据中。我认为问题可能与实体名称有关。 是的,名为“Clinic”的实体存在并且正在完美保存。其他没有“可转换”类型属性的实体在获取时工作正常。这里诊所(以及其他实体!)具有“可变形”类型属性的实体,用于获取崩溃。对于可转换的实体地址,我设置了类型“地址”(另一个模型类)。 @Shirish 我也面临同样的崩溃你有解决方案吗?以上是关于核心数据-[Decodable.Address initWithCoder:]:发送到实例的无法识别的选择器的主要内容,如果未能解决你的问题,请参考以下文章