【问题标题】:Working with Realm in Swift在 Swift 中使用 Realm
【发布时间】: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
}

【问题讨论】:

    标签: ios swift xcode realm


    【解决方案1】:

    这是因为你没有实例化一个领域,所以当你尝试访问它时它是 nil。

    改变

    var realm : Realm!
    

    let realm = try! Realm()
    

    【讨论】:

    • 完全工作!谢谢你^__^
    • @bdash 完成了兄弟 ;-)
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多