在我的应用程序中,我们使用 Realm 存储在本地存储值。我可以将我的数组值存储为 Sting。但无法将值存储和检索为数组。是否可以将 NSArray 值存储到领域对象并将其检索为 NSArray。这是我用来存储字符串值的代码:
class PracticeView: Object
{
dynamic var PracticeArray = ""
}
和用法:
let realm:Realm = try! Realm()
let PracticeDetails = PracticeView()
PracticeDetails.PracticeArray = "Test String Values"
try! realm.write
{
realm.add(PracticeDetails)
}
print("Values In Realm Object: (PracticeDetails.PracticeArray)")
//Result Will Be
Values In Realm Object: Test String Values
不,Realm 不能将原生数组(无论是 Objective-C NSArray
对象还是 Swift 数组(存储为Object
模型类的属性。
在 Realm Swift 中,有一个名为 List
的对象,它允许您将 Realm Object
实例数组存储为子实例。这些仍然不能是字符串,所以有必要将这些字符串封装在另一个 Realm Object
子类中。
class Practice: Object {
dynamic var practice = ""
}
class PracticeView: Object {
let practiceList = List<Practice>()
}
let newPracticeView = PracticeView()
let newPractice = Practice()
newPractice.practice = "Test String Value"
newPracticeView.practiceList.append(newPractice)
let realm = try! Realm()
try! realm.write {
realm.add(newPracticeView)
}
有关更多信息,我建议您查看 Realm Swift 文档的"To-Many Relations"部分。 :)