小编MHC*_*Csk的帖子

将对象数组保存到核心数据

我有一个[User]类型的数组,我想将其保存在Core Data中,然后在表视图中显示它。这是我保存和检索数据的功能:

func saveUserData(_ users: [User]) {
    let context = appDelegate.persistentContainer.viewContext
    let newUser = NSEntityDescription.insertNewObject(forEntityName: "Users", into: context)
    for user in users {
        newUser.setValue(user.id, forKey: "id")
        newUser.setValue(user.name, forKey: "name")
        newUser.setValue(user.email, forKey: "email")
        newUser.setValue(user.phone, forKey: "phone")
        newUser.setValue(user.website, forKey: "website")
        newUser.setValue(user.city, forKey: "city")
        newUser.setValue(user.lat, forKey: "lat")
        newUser.setValue(user.long, forKey: "long")
    }
    do {
        try context.save()
        print("Success")
    } catch {
        print("Error saving: \(error)")
    }
}

func retrieveSavedUsers() -> [User]? {
    let context = appDelegate.persistentContainer.viewContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
    request.returnsObjectsAsFaults = false
    var retrievedUsers: …
Run Code Online (Sandbox Code Playgroud)

core-data uitableview ios swift

1
推荐指数
1
解决办法
1446
查看次数

RealmSwift LinkingObjects 和 Decodable

我有一个 Realm 模型类,我需要它是可解码的,这样我就可以从 JSON 序列化它并将其保存到数据库。每一个PortfolioItem都与一个相关联Product,在某些时候我需要通过逆关系来PortfolioItem访问。Product这就是我拥有LinkingObjects财产的原因。问题是当我试图遵守Decodable协议时。编译器给我一个错误Cannot automatically synthesize 'Decodable' because 'LinkingObjects<PortfolioItem>' does not conform to 'Decodable'。这该如何处理呢?我在网上找到的关于 LinkingObjects 和 Decodable 的信息很少,我不知道如何解决这个问题。

class PortfolioItem: Object {

    @objc dynamic var id: String = ""
    @objc dynamic var productId: String = ""

    @objc dynamic public var product: Product?

    convenience init(id: String, productId: String) {
        self.init()
        self.id = id
    }

}

final class Product: Object, Decodable {

    @objc dynamic var id: String …
Run Code Online (Sandbox Code Playgroud)

realm swift realm-mobile-platform

0
推荐指数
1
解决办法
665
查看次数