gpt4 book ai didi

swift - 通过 Kinvey 使用对象映射

转载 作者:行者123 更新时间:2023-11-30 12:16:09 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com