【问题标题】:Swift- Fetching realm object based on primary keySwift-基于主键获取领域对象
【发布时间】:2018-06-13 03:37:26
【问题描述】:

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

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!)

但是将特定的人设为 nil 但是当我签入表时,这个主键就在那里。有人可以帮忙吗?

【问题讨论】:

    标签: ios swift realm primary-key


    【解决方案1】:

    您必须覆盖默认的 init 方法。为什么不存储整个字典而不是创建多个属性。在这里检查我使用 Data 类完成的代码。您缺少 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 {
    }
    }
    

    【讨论】:

    • 我按照你提到的相同步骤仍然 isAvailable 是假的。
    • 你调用保存函数了吗?
    • 是的,我打过电话。当我检查存在主键的领域表时。
    • 您能否更新修改后的代码以及您在哪里使用值调用保存函数?确保存储字典不为空
    猜你喜欢
    • 1970-01-01
    • 2015-09-24
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    相关资源
    最近更新 更多