swift - 如何从Sqlite数据库加载表视图中的数据,UISwitch的状态是根据数据库中的保存状态
问题描述
我想TableView
从 DataBase(SQlite) 加载数据,并UISwitch
根据DataBase
. 这是我的代码
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ParentalMovieTableViewCell", for: indexPath) as! ParentalMovieTableViewCell
let db = xxxDataBase()
lockArray = db.getLockInfo(catg: tabName)
if lockArray.isEmpty == true
{
cell.itemLbl.text = parentalMovieArray[indexPath.row]
cell.itemSwitch.isOn = true
cell.itemSwitch.tag = indexPath.row
cell.itemSwitch.addTarget(self, action: #selector(self.switchChanged(_sender:)), for: .valueChanged)
}
else
{
cell.itemLbl.text = parentalMovieArray[indexPath.row]
cell.itemSwitch.tag = indexPath.row
cell.itemSwitch.addTarget(self, action: #selector(self.switchChanged(_sender:)), for: .valueChanged)
for i in parentalMovieArray
{
for j in lockArray{
if i == j.item
{
cell.itemSwitch.isOn = true
}
else
{
cell.itemSwitch.isOn = false
}
}
}
}
@objc func switchChanged(_sender:UISwitch!)
{
// print("Table view switch changed\(_sender.tag)")
// print("The switch is\(_sender.isOn ? "ON" : "OFF")")
if _sender.isOn == false
{
print(_sender.tag)
var value = parentalMovieArray[_sender.tag]
print(value)
restrictMovieArray.append(value)
print(restrictMovieArray)
}
else if _sender.isOn == true
{
print(_sender.tag)
var value1 = parentalMovieArray[_sender.tag]
print(value1)
if let index = restrictMovieArray.index(of: value1) {
restrictMovieArray.remove(at: index)
print(restrictMovieArray)
}
}
}
解决方案
1-)在委托方法中从数据库中检索数据tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
实际上是非常昂贵的,因为它会被调用很多次,尤其是当用户滚动时,它会降低您的应用程序性能,常见的解决方案是获取数据 viewDidLoad
并将其存储在 viewcontrollers 成员中并使用它当你需要的时候。
2-)if lockArray.isEmpty == true
和else
块的前 3 行相同,因此您可以将其移动到这些块下方。
你能澄清你的问题吗?
推荐阅读
- google-app-engine - 查找返回空数据集的数据库中的记录的方法
- r - 如何找到向量变化的特定时间
- python - 在 K8s pod 中运行的 Logstash 容器的 http 插件使用什么主机和端口?
- json - json-diff diffString 输出中没有颜色
- html - HTML CSS 在矩形中心对齐文本
- vue.js - 如何使用 jest 在单元测试中测试引导 vue 组件的存在?
- c# - 当 Json 的节点是不断变化的日期时,如何解析 Json 响应?
- ffmpeg - FFMPEG:忽略转换是设置是一样的
- wordpress - 如何为我的 pwa 编写安装提示
- python - IndexError:使用 selenium 列出超出范围的索引