【发布时间】:2021-05-07 16:57:18
【问题描述】:
我有一个函数可以将领域表中的所有对象打印到表视图中。我希望能够通过它们的“肌肉”属性过滤这些对象。
这是我的数据库助手函数:
func getMusclesCount()-> Int {
let storedExercise = realm.objects(StoredExercise.self)
return storedExercise.count
}
//MARK:- getAllMuscelsNames
func getAllMusclesNames()-> [String] {
var musclesName = [String]()
let storedExercise = realm.objects(StoredExercise.self)
for exercise in storedExercise {
print("Muscle = \(exercise.muscle)")
musclesName.append(exercise.name)
}
return musclesName
}
这是我的表视图控制器类:
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DBHelper.shared.getAllMusclesNames().count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
let muscle = DBHelper.shared.getAllMusclesNames()[indexPath.row]
cell.textLabel?.text = muscle
return cell
}
我尝试将 .Filter 添加到 'let storedExercise' 但我不确定如何正确设置它。任何帮助将不胜感激,谢谢。
【问题讨论】:
-
几件事。最好在问题中包含您的 Realm 模型,以便我们知道它们的样子。其次,您可能不想将您的领域结果转换为数组 - 请参阅我的回答 here。最后,
getMusclesCount如何与问题中的其余代码一起工作,我没有看到任何对它的引用。 -
哦,最后,您不会希望以这种方式填充您的 tableView。 Tableview 委托方法应该是轻量级和快速的,每次从磁盘或存储中提取数据并不是一个好主意 - 你需要在内存中保留一个
results对象 - 这也可以追溯到不投射结果到一个数组。
标签: ios swift xcode uitableview realm