[英]Realm init for storyboard tableview
我在使用Storyboard ViewController实现同步领域时遇到问题。
具体来说,我不确定如何提供初始化程序。
如果我以编程方式创建ViewController,则可以使用以下内容,并且一切正常。 但是,我正在使用情节提要。 该代码由领域教程提供。
import UIKit
import RealmSwift
class ItemsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let realm: Realm
let items: Results<Item>
let refresh = UIRefreshControl()
let tableView = UITableView()
var notificationToken: NotificationToken?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
let syncConfig = SyncConfiguration(user: SyncUser.current!, realmURL: Constants.REALM_URL)
self.realm = try! Realm(configuration: Realm.Configuration(syncConfiguration: syncConfig, objectTypes:[Item.self]))
self.items = realm.objects(Item.self).sorted(byKeyPath: "body", ascending: true)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
notificationToken?.invalidate()
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Items to Get Done"
tableView.dataSource = self
tableView.delegate = self
view.addSubview(tableView)
tableView.frame = self.view.frame
....
这不适用于情节提要ViewConroller,因为(据我所知)情节提要正在配置和初始化ViewConroller。
然后我的问题是,如何以及在哪里编写该init?
您可以在ViewDidLoad中编写领域加载。
import UIKit
import RealmSwift
class ItemTableViewController: UITableViewController {
var realm!
var items: Results<Item>?
override func viewDidLoad() {
super.viewDidLoad()
self.loadItems()
}
//Readcategory:
func loadItems() {
let syncConfig = SyncConfiguration(user: SyncUser.current!, realmURL: Constants.REALM_URL)
self.realm = try! Realm(configuration: Realm.Configuration(syncConfiguration: syncConfig, objectTypes:[Item.self]))
self.items = realm.objects(Item.self).sorted(byKeyPath: "body", ascending: true)
self.tableView?.reloadData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items?.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath) as! SwipeCell
if let item = self.items?[indexPath.row] {
cell.textLabel?.text = item.title
}
return cell
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.