swift - 通过 Kinvey 使用对象映射

标签 swift xcode kinvey

我有一组对象,我正试图从我的一个集合中取出。我一直在使用他们的文档和一些谷歌搜索,我相信我已经接近解决方案,但还不够接近。这是我所拥有的:

class Clothing: Entity {

    var categories: [Category]!
    var gender: String!

    override class func collectionName() -> String {
    //return the name of the backend collection corresponding to this entity
        return "categories"
    }

    override func propertyMapping(_ map: Map) {
        super.propertyMapping(map)

        categories <- map["clothing"]
        gender <- map["gender"]

    }
}


class Category: NSObject, Mappable{

    var title: String?
    var image: String?

    convenience required init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        title <- map["category"]
        image <- map["image"]
    }
}

我能够获得正确的性别,但类别数组似乎没有映射到类别对象。有什么想法吗?

最佳答案

您的模型实际上有一个问题,如您在 https://devcenter.kinvey.com/ios/guides/datastore#Model 中看到的那样你应该使用let categories = List<Category>()而不是var categories: [Category]! 。这是经过测试并有效的模型:

import Kinvey

class Clothing: Entity {

    let categories = List<Category>()
    var gender: String!

    override class func collectionName() -> String {
        //return the name of the backend collection corresponding to this entity
        return "clothing"
    }

    override func propertyMapping(_ map: Map) {
        super.propertyMapping(map)

        categories <- ("categories", map["categories"])
        gender <- ("gender", map["gender"])

    }
}

class Category: Object, Mappable{

    var title: String?
    var image: String?

    convenience required init?(map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        title <- ("category", map["category"])
        image <- ("image", map["image"])
    }
}

这是如何保存新的 Clothing 的示例代码对象

let casualCategory = Category()
casualCategory.title = "Casual"

let shirtCategory = Category()
shirtCategory.title = "Shirt"

let clothing = Clothing()
clothing.gender = "male"
clothing.categories.append(shirtCategory)
clothing.categories.append(casualCategory)

dataStore.save(clothing) { (result: Result<Clothing, Swift.Error>) in
    switch result {
    case .success(let clothing):
        print(clothing)
    case .failure(let error):
        print(error)
    }
}

关于swift - 通过 Kinvey 使用对象映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45417862/

相关文章:

ios - 使用 Facebook 的移动主机 API 时,有没有办法通过 FBSDKAppInviteContent 传递自定义数据?

ios - 如何在自定义 UITableViewCell 中获取 UILabel 的字体大小?

xcode - 在按下 "Add"按钮之前,阵列 Controller 不会更新 TableView

ios - 我的 Xcode 项目坏了吗

android - 收到多条推送通知

android - 在 Kinvey (Android) 中创建集合

swift - 无法出示 Apple Pay 授权 Controller

ios - 如何将项目从初始(一次)第一次 View Controller 传递到主视图 Controller 并使用核心数据保存该数据

ios - 加载新 View 时如何禁用 UISwipeGestureRecognizer?

swift - 解析为 Kinvey 查询