I have the following code in my 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")
}
}
There is a considerable difference in the smoothness of the scrolling when i put back in the commented out portion.
This is just a query to retrieve some info, i didn't have directly in my tableview's data source. How can I optimise this?
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
}
}
A Realm lookup is usually quite fast but it is still an async task which takes time and may even run on another thread.
Rather than doing this every time you attempt to render a cell I would suggest that you fetch all Types (maybe in viewDidLoad) and then just filter in cellForRow
Then you can just do something like
cell.add = types.first { $0.id == subC.type } ?? ""
Which is not aysnc and will be much faster and more responsive
If for some reason you can't fetch all types, I would at least cache the results as you get them.