无法将Appdata类型的值转换为预期的参数类型Object.type Realm Swift

时间:2016-12-24 15:18:20

标签: swift realm

如何在IOS App中检索Realm对象数据?

Object类将是:

import Foundation
import RealmSwift


class AppData: Object {

  dynamic var id = 0
  dynamic var tokeType = ""
  dynamic var token = ""
  dynamic var refreshToken = ""
  dynamic var accessToken = ""

  override static func primaryKey() -> String? {
    return "id"
  }

}

我用来填充/更新AppData Realm对象的下一个函数:

func register(_ instanceParameters : [String : AnyObject], completionHandler: @escaping ([Instance]?, NSError?) -> ()) {

    Alamofire.request(Router.register(instanceParameters)).responseJSON{ response in

      var instance = [Instance]()

      let AppDataObj = AppData()
      let config = Realm.Configuration(
        schemaVersion: 1,
        migrationBlock: { migration, oldSchemaVersion in
          if (oldSchemaVersion < 1) {
          }
      })
      Realm.Configuration.defaultConfiguration = config
      let realm = try! Realm()


      switch response.result {
      case .success(let json):
        let responseObject = json as? [String: AnyObject]
        instance.append(Instance(dictionary: responseObject!))

        AppDataObj.token = (instance.first?.token)!
        AppDataObj.tokeType = "Instance_Token"
        AppDataObj.id = 1

        try! realm.write {
          realm.add(AppDataObj, update: true)
        }   
        completionHandler(instance, nil)
      case .failure(let error):
        completionHandler(nil, error as NSError)
      }
    }
  }

目前一切正常,你可以在下面看到我可以使用Realm Browser管理AppData对象:

enter image description here

我发现的问题是当我需要使用Realm Object Data for Persistence试图检索AppData令牌时:

import RealmSwift

var AppDataObj = AppData()

let data = realm.object(ofType: AppDataObj, forPrimaryKey: "id")
loginParameters["token"] = AppDataObj.token as AnyObject? --> this line throws the error defined in the title of this question

1 个答案:

答案 0 :(得分:0)

你应该先正式指导https://realm.io/docs/swift/latest/

首先,当您想要获取持久对象时,您不需要创建Realm对象的实例。

其次,您应该将实际值传递给forPrimaryKey参数,而不是属性名称。您将对象保存为id = 1,因此它应为realm.object(ofType: AppDataObj, forPrimaryKey:)`。

object(ofType:forPrimaryKey:)方法返回一个Realm对象。所以正确的代码是:

import RealmSwift

let data = realm.object(ofType: AppDataObj, forPrimaryKey: 1)
loginParameters["token"] = data.token