与Kinvey一起使用对象映射

时间:2017-07-31 13:54:20

标签: 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"]
    }
}

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

1 个答案:

答案 0 :(得分:0)

您的模型实际上有一个问题,正如您在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)
    }
}