【发布时间】:2017-06-23 21:28:59
【问题描述】:
我想创建一个使用 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
}
【问题讨论】: