我想创建一个使用 Realm 存储联系人的电话簿。当我尝试检索对象时,由于对象是nil
. 我不确定我应该做什么:
我的代码看起来像这样:
// MainVC.swift:
import UIKit
import RealmSwift
class MainVC: UIViewController,UITableViewDelegate,UITableViewDataSource{
@IBOutlet weak var contact_tableview: UITableView!
var realm : Realm!
var ContactList: Results<Contact> {
get {
return realm.objects(Contact.self)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.titleTextAttributes =
[NSFontAttributeName: UIFont(name: "IRANSansWeb-Medium", size: 17)!]
contact_tableview.delegate = self
contact_tableview.dataSource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ContactList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "contactcell") as! ContactCell
let item = ContactList[indexPath.row]
cell.lblName!.text = item.first_name
return cell
}
}
// Contact.swift:
import Foundation
import RealmSwift
class Contact: Object {
dynamic var first_name = ""
dynamic var last_name = ""
dynamic var work_email = ""
dynamic var personal_email = ""
dynamic var contact_picture = ""
dynamic var mobile_number = ""
dynamic var home_number = ""
dynamic var isFavorite = false
}
因为你没有实例化一个领域,所以当你尝试访问它时它是零。
改变
var realm : Realm!
至
let realm = try! Realm()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句