Swift 仅在 cellforrow 中进行一次查询,tableview 的显着提升

Swift considerable jump in tableview with just one query in cellforrow

我的 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")
        }

    }

我把注释掉的部分放回去,滚动的流畅度有很大的不同

这只是一个检索一些信息的查询,我没有直接在我的表视图的数据源中。我该如何优化它?

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
        }
    }

Realm 查找通常很快,但它仍然是一个异步任务,需要时间,甚至可能 运行 在另一个线程上。

与其每次尝试渲染单元格时都这样做,我建议您获取所有类型(可能在 viewDidLoad 中),然后在 cellForRow

中过滤

然后你可以做类似

的事情
cell.add = types.first { [=10=].id == subC.type } ?? ""

这不是 aysnc,而且速度更快,响应更快

如果由于某种原因您无法获取所有类型,我至少会在您获取结果时缓存它们。