2017-06-23 20 views
1

レルムを使用して連絡先を保存する電話帳を作成したいとします。オブジェクトを取得しようとすると、オブジェクトがnilであるためにエラーが発生します。私は何をすべきかわからない:Swiftでレルムを使用する

enter image description here enter image description here

私のコードはそうのようになります。あなたがしようとすると、それが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 
} 

答えて

2

そのアクセスしてください。

let realm = try! Realm() 
+0

に変更

var realm : Realm! 

は完全に働きました!ありがとうございました^ __^<3 –

+0

@AmirMohammadGholami、あなたの問題を解決した場合、回答を受け入れてください。 – bdash

+0

@bdash完了;-) <3 –

関連する問題