【问题标题】:Realm Swift: instance member cannot be used on typeRealm Swift:实例成员不能用于类型
【发布时间】:2017-01-19 08:02:32
【问题描述】:

我收到此错误:

“Realm Swift:实例成员 'Int' 不能用于类型 'Comment'”

我发现this answer 建议使用关键字static。但是,由于我正在编写的函数的目的是在创建对象之后访问主键,因此使用静态变量是行不通的。

有什么改进的建议吗?

import Foundation
import RealmSwift

class Comment: Object {
    dynamic var id : Int = -1 

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

【问题讨论】:

  • primaryKey 函数应该返回主键变量的变量名,而不是值,所以你应该返回“id”而不是参考:realm.io/docs/swift/latest/#primary-keys
  • 谢谢!没有意识到..现在我明白了..Realm 接受纯字符串作为引用内部变量的方式.. 很好很简单。

标签: ios swift realm


【解决方案1】:

在对我有用的 cmets 中引用“@Octaviano Putra”:

primaryKey 函数应该返回主键的变量名 变量,而不是值,所以你应该返回“id”而不是参考: realm.io/docs/swift/latest/#primary-keys

【讨论】:

    【解决方案2】:

    类型方法不能直接访问实例属性

    我将添加此答案以解释明显的错误消息 [emphasis mine]:

    “Realm Swift:instance member 'Int' 不能在类型上使用 'Comment'”

    type 方法无法访问该类型的 instance members,除非显式访问该类型本身的 实例(它没有,在你上面的例子中)。

    来自the Language Guide - Methods

    类型方法

    如上所述,实例方法是被调用的方法 特定类型的实例。您还可以定义方法 在类型本身上调用。这些类型的方法称为类型方法。您可以通过编写 static 来指示类型方法 方法的 func 关键字之前的关键字。类也可以使用 class 关键字允许子类覆盖超类的 该方法的实现。

    class Foo {
        // this is an _instance_ property, accessible to
        // _instances_ of the _type_ 'Foo'
        let instanceProperty: Int
    
        // this is a _type method_, owned by the _type_ 'Foo'
        class func typeMethod() -> String {
            // this method knows nothing about the _content_ of
            // particular instances of of the type itself (unless
            // we explictly provide this information to the method)
            return "foo"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-24
      • 2023-03-24
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      • 2016-05-23
      • 2016-01-01
      相关资源
      最近更新 更多