[英]Swift And CoreData With Custom Class As Transformable Object
我試圖使用swift和CoreData作為可轉換對象的自定義類。 我一直在浪費時間試圖弄清楚但不能。 我不斷收到兩個錯誤:屬性無法標記為@NSManaged,因為其類型無法在Objective-C中表示,並且Property無法聲明為public,因為其類型使用內部類型。
非常感謝幫助。 謝謝。
我有一個名為User的CoreData對象。 我還有一個名為Site的對象。
我不希望Site對象成為CoreData對象,因為我創建Site對象的大多數時候我不希望它添加到CoreData上下文。
您將在下面看到“site”類型的“primarySite”和“Site”類型的“sites”。 這兩行給出了我上面列出的兩個錯誤。
用戶+ CoreDataClass
import Foundation
import CoreData
public class User: NSManagedObject {
}
用戶+ CoreDataProperties
import Foundation
import CoreData
extension User {
@nonobjc public class func fetchRequest() -> NSFetchRequest<User> {
return NSFetchRequest<User>(entityName: "User");
}
@NSManaged public var firstName: String?
@NSManaged public var lastName: String?
@NSManaged public var role: String?
@NSManaged public var primarySite: Site
@NSManaged public var sites: [Site]
}
現場
import UIKit
class Site: NSCoding {
let identifier: Int32
let name: String
let note: String
init(with values: Dictionary<String,Any>) {
identifier = Int32(values["identifier"] as! String)!
name = values["name"] as! String
note = values["note"] as! String
}
required convenience init(coder decoder: NSCoder) {
var siteValues = [String:Any]()
siteValues["identifier"] = decoder.decodeObject(forKey: "identifier") as! String
siteValues["name"] = decoder.decodeObject(forKey: "name") as! String
siteValues["note"] = decoder.decodeObject(forKey: "note") as!
self.init(with: siteValues)
}
func encode(with coder: NSCoder) {
coder.encode(String(self.identifier), forKey: "identifier")
coder.encode(self.name, forKey: "name")
coder.encode(self.note, forKey: "note")
}
}
Property cannot be marked @NSManaged because its type cannot be represented in Objective-C
發生這種情況是因為Site
不從NSObject
繼承。 Swift類不必從NSObject
繼承,但Core Data轉換可以繼承。 如果添加NSObject
,則不會發生該錯誤。
還有一些其他問題 - 你的init(coder decoder: NSCoder)
沒有分配任何屬性值,例如 - 但這些應該很容易理解。
我想出了如何解決這兩個錯誤。
1) “屬性不能標記為@NSManaged,因為它的類型不能用Objective-C表示”
感謝@ Tom的回答我通過使Site成為NSObject的子類來解決這個錯誤。
class Site: NSObject, NSCoding {
2) “屬性不能公開,因為它的類型使用內部類型”
我通過在類之前添加“public”以及編碼器和解碼器功能來解決此錯誤。
public class Site: NSObject, NSCoding {
...
public func encode(with coder: NSCoder) {...}
public required convenience init(coder decoder: NSCoder) {...}
由於Site是自定義類,因此不能將其用作NSManagedObject中的數據類型。
就我而言,我在您的數據模型中創建了“二進制數據”類型。 因此,使其類型NSData成為目標c中的數據類型。
在此之后,您可以取消歸檔數據。
例如:
if let sitesArray = NSKeyedUnarchiver.unarchiveObject(with: sites) as? [[String : Any]] {
//enter your processing code here to convert them to site objects
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.