滚动时TableView滞后

时间:2016-04-25 14:32:52

标签: ios swift uitableview realm freeze

滚动表格时会出现滞后现象。图片或数据库中的长文本不会。对不起,我的英文不好

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("audioCell", forIndexPath: indexPath) as? AudiosTableViewCell

    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "audioCell") as? AudiosTableViewCell
    } else {
        let realm = try! Realm()
        let audios = realm.objects(Music)[indexPath.row]
        let duration = audios.duration
        var durationString = ""

        if duration/60 < 10 {
            durationString = durationString + "0" }
        durationString = durationString + String(duration/60) + ":"
        if duration%60 < 10 {
            durationString = durationString + "0" }
        durationString = durationString + String(duration%60)

        cell!.artistLabel.text = audios.artist
        cell!.titleLabel.text = audios.title
        cell!.durationLabel.text = durationString
    }
    return cell!
}

如果您需要其他信息,请准确撰写您需要的信息。我已经审查了很多信息,尝试了很多方法,第三天我受苦了,它不起作用

3 个答案:

答案 0 :(得分:2)

    let realm = try! Realm()

应该在videoDidLoad或类似内容上完成,但只有我建议

if audios.count == 0 {
        let realm = try! Realm()
        let audios = realm.objects(Music)[indexPath.row]
}

然后替换

    let realm = try! Realm()
    let audiosStore = realm.objects(Music)

let audios = audiosStore[indexPath.row]

致电时

    let realm = try! Realm()

每次都要求Realm中的所有对象。

答案 1 :(得分:0)

您可以将此代码移出cellForRow,并确保在cellForRow触发之前调用它。

let realm = try! Realm()

答案 2 :(得分:0)

tableView.dequeueReusableCellWithIdentifier("audioCell", forIndexPath: indexPath)永远不会返回nil。如果您已经知道单元格将具有类AudiosTableViewCell,则可以按如下方式重写代码:

// Make realm property of your view controller
    let realm: Realm!

// In viewDidLoad
    realm = try! Realm()


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("audioCell", forIndexPath: indexPath) as! AudiosTableViewCell

    let audios = realm.objects(Music)[indexPath.row]
    let duration = audios.duration
    var durationString = ""

    if duration/60 < 10 {
        durationString = durationString + "0" }
    durationString = durationString + String(duration/60) + ":"
    if duration%60 < 10 {
        durationString = durationString + "0" }
    durationString = durationString + String(duration%60)

    cell.artistLabel.text = audios.artist
    cell.titleLabel.text = audios.title
    cell.durationLabel.text = durationString
    return cell
}