Search code examples
iosswiftxcoderealm

Working with Realm in Swift


I want to create a phonebook that stores contacts using Realm. When I try to retrieve objects, some errors occur due to an object being nil. I'm not sure what I should do:

enter image description here enter image description here

My code looks like so:

// 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
}

Solution

  • Its because you didn't instantiate a realm, so it's nil when you try and access it.

    Change

    var realm : Realm!
    

    to

    let realm = try! Realm()