Swift-基于主键获取领域对象

时间:2018-06-13 03:37:27

标签: ios swift realm primary-key

我正在使用Realm离线存储数据。我需要根据主键获取行,但我的响应是nil。 这是我的Model类

import UIKit
import RealmSwift

class DCContactListModel: Object {

    @objc dynamic var mProfile_pic:String?
    @objc dynamic var mSalutation:String?
    @objc dynamic var mStatus:String?
    @objc dynamic var mTitle:String?
    @objc dynamic var mUid:String?

    //property

     var mUserIndex: Int?
     var mIsSelected = false


    override class func primaryKey() -> String {
        return "mUid"
    }

    func initWithUserChatDictionary(userDictionary:Dictionary<String, Any>) -> DCContactListModel{

        if let profile_pic = userDictionary["profile_pic"] {
            mProfile_pic = profile_pic as? String
        }
        if let salutation = userDictionary["salutation"] {
            mSalutation = salutation as? String
        }
        if let status = userDictionary["status"] {
            mStatus = status as? String
        }
        if let title = userDictionary["title"] {
            mTitle = title as? String
        }
        if let uid = userDictionary["uid"] {
            mUid = uid as? String
        }

        return self
    }
} 

这里我添加了使用对象

访问数据的代码
let primaryKey = "8687tuyguyhytu6ruf76fyt7"
 let realm = try! Realm()
 let specificPerson = realm.object(ofType: DCContactListModel.self, forPrimaryKey: primaryKey)
        print(specificPerson!)

但是将特定的人定为零但是当我在桌子上检查时,这个主键就在那里。有人可以帮忙。

1 个答案:

答案 0 :(得分:0)

您必须覆盖默认的init方法。为什么不存储整个字典而不是创建多个属性。在这里查看我使用数据类完成的代码。您缺少init方法,这可能是问题所在。

convenience init(userDictionary:Dictionary<String, Any>) {
 self.init()
    if let profile_pic = userDictionary["profile_pic"] {
            mProfile_pic = profile_pic as? String
        }
        if let salutation = userDictionary["salutation"] {
            mSalutation = salutation as? String
        }
        if let status = userDictionary["status"] {
            mStatus = status as? String
        }
        if let title = userDictionary["title"] {
            mTitle = title as? String
        }
        if let uid = userDictionary["uid"] {
            mUid = uid as? String
        }
}

<强> Sample.swift

import Foundation
import RealmSwift

class Sample: Object {

// Specify properties to ignore (Realm won't persist these)

//  override static func ignoredProperties() -> [String] {
//    return []
//  }
    private(set) dynamic var sectionName = ""
    private(set) dynamic var data = Data()

    /**
     Override Object.primaryKey() to set the model’s primary key. Declaring a primary key allows objects to be looked up and updated efficiently and enforces uniqueness for each value.
     */
    override static func primaryKey() -> String? {
        return "sectionName"
    }

    convenience init(sectionName: String, data: Data) {
        self.init()
        self.sectionName = sectionName
        self.data = data
    }
}





//MARK: DATABASE CODE
    func saveData(data:Data, sectionName:String) -> Void {
        let obj = Sample(sectionName: sectionName, data: data)
        let realm = try! Realm()
        try! realm.write({
            // If update = true, objects that are already in the Realm will be
            // updated instead of added a new.
            realm.add(obj, update: true)
        })
    }
    func deleteData(sectionName:String){
        let realm = try! Realm()
        let data = realm.object(ofType: Sample.self, forPrimaryKey: sectionName)
        if data != nil{
            try! realm.write {
                realm.delete(data!)
            }
        }
    }
    func getData(sectionName:String,completion: @escaping (_ Data: Data, _ isContain:Bool) -> Void){
        let realm = try! Realm()
        let data = realm.object(ofType: Sample.self, forPrimaryKey: sectionName)
        if data != nil{
            completion((data?.data)!, true)
        }else{
            completion(Data(), false)
        }

    }

样本使用

self.deleteData(sectionName:"primary key")
        self.saveData(data: result, sectionName:"primary key")

self.getData(sectionName: "primary key") { (data, isAvailable) in
            if isAvailable {
}
}