在Realm中追加结果数组

Duy*_*yen 1 append realm nsarray ios swift3

大家早上好,

我有一个表视图,显示从2个不同类保存的对象.我将这些结果组合成一个数组,以显示在tableView中.这是我的代码:

import UIKit
import RealmSwift

class BookmarksVC: UIViewController,UITableViewDelegate,UITableViewDataSource {

var articleList: Results<DynamicObject>!
var documentList: Results<DynamicObject>!
var list = [Any]()
var article: Any!
var searchBar:UISearchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 280, height: 20))

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(UINib(nibName: "BookmarkCell", bundle: nil), forCellReuseIdentifier: "bookmarkCell")
    tableView.delegate = self
    tableView.dataSource = self
    drawNavBarUI(navigationItem: self.navigationItem, searchBar: searchBar)
    loadDataAndUpdateUI()
}

func loadDataAndUpdateUI() {
    articleList = realm.dynamicObjects(NewsArticle.className())
    documentList = realm.dynamicObjects(Documents.className())
    list.append(articleList)
    list.append(documentList)
    tableView.setEditing(false, animated: true)
    tableView.reloadData()
}
Run Code Online (Sandbox Code Playgroud)

但结果是:

在此输入图像描述

它导致tableview只显示2个单元格.我试图使用append(ContentsOf :)但是Xcode强制它回到append().这是我第一次使用Realm,所以我可能对它没有深刻的理解.所以任何人都可以帮我解决这个问题?谢谢大家阅读,抱歉我的英语不好.

kis*_*umi 7

来自Realm的Katsumi在这里.我们不建议将Results对象复制到Array.它失去了Results诸如自动更新,延迟加载等有用的能力.此外,使用DynamicObject丢失类型安全.

Results即使您有多个Results对象,也可以直接用作数据源.如下:

class BookmarksVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
    var articleList: Results<NewsArticle>!
    var documentList: Results<Documents>!

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        ...

        loadDataAndUpdateUI()
    }

    func loadDataAndUpdateUI() {
        articleList = realm.objects(NewsArticle.self)
        documentList = realm.objects(Documents.self)

        ...

        tableView.reloadData()
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return articleList.count + documentList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        if indexPath.row < articleList.count {
            let article = articleList[indexPath.row]
            let cell = tableView.dequeueReusableCell(withIdentifier: "bookmarkCell", for: indexPath) as! BookmarkCell
            cell.configureCell(article: article)
            return cell
        } else {
            let document = documentList[indexPath.row - articleList.count]
            ...
        }
    }

    ...

}
Run Code Online (Sandbox Code Playgroud)