Realm Platform数据未使用Storyboard-Swift 4加载到TableView中

时间:2018-10-09 11:10:41

标签: ios swift uitableview realm realm-mobile-platform

大家好,这是我的问题,我一直在Realm Platform待办事项列表应用程序中关注,但是我正在根据自己的需求对其进行自定义。该项目最初是用没有情节提要构建的,但是我想使用情节提要。我无法获得tableView来显示来自领域平台的数据。数据将添加内容写入平台,但不会传递到tableView中。有什么建议吗?

谢谢

科尔。

代码如下:

import UIKit
import RealmSwift
import SVProgressHUD
import SwipeCellKit

class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var tableView: UITableView!
    @IBOutlet weak var quickNotes: UITextView!

    //Create our Realm File
    let realm = try! Realm(configuration: SyncConfiguration.automatic())
    var items: Results<Items>?
    var notificationToken: NotificationToken?
    var subscriptionToken: NotificationToken?
    var subscription: SyncSubscription<Items>!
    var notes: Results<Notes>?

    override func viewDidLoad() {
        super.viewDidLoad()



        //Load our Realm Object into the view

        tableView.rowHeight = 70.0
        tableView.delegate = self
        tableView.dataSource = self
        tableView.reloadData()
        loadCategory()
        subscription = items?.subscribe(named: "my-projects")

        subscriptionToken = subscription.observe(\.state, options: .initial) { state in
            if state == .complete {

            } else {
                print("Subscription State: \(state)")
            }
        }


        notificationToken = items?.observe { [weak self] (changes) in
            guard let tableView = self?.tableView else { return }
            switch changes {
            case .initial:
                // Results are now populated and can be accessed without blocking the UI
                tableView.reloadData()
            case .update(_, let deletions, let insertions, let modifications):
                // Query results have changed, so apply them to the UITableView
                tableView.beginUpdates()
                tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }),
                                     with: .automatic)
                tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}),
                                     with: .automatic)
                tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }),
                                     with: .automatic)
                tableView.endUpdates()
            case .error(let error):
                // An error occurred while opening the Realm file on the background worker thread
                fatalError("\(error)")
            }
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "categoryCell", for: indexPath)

        cell.textLabel?.text = items?[indexPath.row].name ?? "There were no categories added"

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let item = items?[indexPath.row]
        let listItemsVC = CloudListViewController()
        listItemsVC.project = item
        performSegue(withIdentifier: "segueToCloudLists", sender: self)
        tableView.deselectRow(at: indexPath, animated: true)
    }

    //Add List Item to Database
    @IBAction func quickAdd(_ sender: UIBarButtonItem) {
        let alertController = UIAlertController(title: "Add New Project", message: "", preferredStyle: .alert)

        alertController.addAction(UIAlertAction(title: "Save", style: .default) { _ in
            let textField = alertController.textFields![0]
            let item = Items()
            item.name = textField.text ?? "Nothing was added"

            try! self.realm.write {
                self.realm.add(item)

                let user = self.realm.object(ofType: PermissionUser.self, forPrimaryKey: SyncUser.current!.identity!)!
                let permission = item.permissions.findOrCreate(forRole: user.role!)
                permission.canRead = true
                permission.canUpdate = true
                permission.canDelete = true
            }
        })
        alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        alertController.addTextField() { textField in
            textField.placeholder = "New Item Text"
        }
        self.present(alertController, animated: true, completion: nil)
    }
}

1 个答案:

答案 0 :(得分:0)

我想您正在items函数中加载loadCategory(不能确定,因为您省略了该函数的定义)。

您需要在将数据检索到数据源结构中(在您的情况下为tableView.reloadData()之后而不是在此之前)中调用items

...
loadCategory()
subscription = items?.subscribe(named: "my-projects")
tableView.reloadData()
...