我的班级定义为:
class Device: Object {
dynamic public var assetTag = ""
dynamic var location = ""
}
我还有两个数组定义为:
let array = ["12", "42", "52", "876"]
let array2 = ["SC", "EDS", "DS", "EF"]
我想遍历第一个数组并将每个值添加到我的领域 Device.assetTag 对象并遍历我的第二个数组并将每个值添加到 Device.location 对象。
我尝试使用 Realm 自述文件中的代码从第一个数组中添加数据,但它似乎没有循环:
let realmArray = Device(value: array)
let realm = try! Realm()
try! realm.write {
realm.add(realmArray)
}
您有两个数组,一个包含 asetTags 和另一个位置,因此首先您必须从这些数组构建对象。您可以执行以下操作(可能需要重构)
class Device: Object {
dynamic public var assetTag = ""
dynamic var location = ""
}
class Test {
let assetTags = ["12", "42", "52", "876"]
let locations = ["SC", "EDS", "DS", "EF"]
func saveDevice() {
let realm = try! Realm()
try! realm.write {
let allDevices = getDeviceArray()
for device in allDevices {
realm.add(device)
}
}
}
func getDeviceArray() -> [Device] {
let requiredDevices = [Device]()
var index = 0
for tag in assetTags {
let locationForTag = locations[index]
let device = Device()
device.assetTag = tag
device.location = locationForTag
requiredDevices.append(device)
index += 1
}
return requiredDevices
}
}
记住在realm.write 中放置循环以进行批量操作,这确保了一次写入连接。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句