我的willDisplay中有以下代码:
func tableView(_: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard case let cell as L_LocCell = cell else {
return
}
let subC = subContractors[indexPath.row]
cell.backgroundColor = .clear
cell.locName = subC.companyname
cell.locCode = subC.region
/*if let sType = Helper_Types.getType(subC.type)
{
cell.add = sType.name
}
else {
cell.add = ""
}*/
switch subC.status {
case 3:
cell.catColor = UIColor(rgba: Palette.class_bad)
cell.catName = "Declined"
break
case 2:
cell.catColor = UIColor(rgba: Palette.class_good)
cell.catName = "Approved"
break
case 1:
cell.catColor = UIColor(rgba: Palette.class_warn)
cell.catName = "Pending"
break
case 4:
cell.catColor = UIColor(rgba: Palette.ok)
cell.catName = "Approved with Exception"
break
default:
cell.catColor = companyMed
cell.catName = "Unknown"
break
}
if subConPicDir != nil {
let filename = subConPicDir!.appendingPathComponent(subC.subcontractorId.description+".jpg")
cell.thumbImg.kf.setImage(
with: filename,
placeholder: UIImage(named: "ic_supplier")!,
options: [.transition(.fade(1)), .cacheOriginalImage],
progressBlock: { receivedSize, totalSize in
},
completionHandler: { result in
print(result)
})
}
else{
cell.thumbImg.image = UIImage(named: "ic_supplier")
}
}
当我放回注释掉的部分时,滚动的平滑度会有很大的差异。
这只是一个检索某些信息的查询,我没有直接在tableview的数据源中使用。我该如何优化呢?
public static func getType(_ tid: Int) -> Types?
{
do {
var realm : Realm? = try Realm()
let predicate = NSPredicate(format: "_id = %d", tid);
let types = realm!.objects(STD_type.self).filter(predicate);
realm = nil
if types.count > 0
{
return Types(st : types.first!)
} else {
return nil;
}
} catch let error as NSError {
print("error realm \(error.localizedDescription)")
return nil
}
}
答案 0 :(得分:0)
Realm查找通常非常快,但它仍然是一个异步任务,需要花费时间,甚至可能在另一个线程上运行。
建议您先提取所有类型(也许在viewDidLoad中),然后再过滤cellForRow
然后您可以做类似
的操作cell.add = types.first { $0.id == subC.type } ?? ""
不是aysnc的人,它将更快,响应更快
如果由于某种原因您无法获取所有类型,那么我至少会在获取结果时将其缓存。