简体   繁体   English

Realm Swift:实例成员不能在类型上使用

[英]Realm Swift: instance member cannot be used on type

I am getting this error: 我收到此错误:

"Realm Swift: instance member 'Int' cannot be used on type 'Comment'" “ Realm Swift:实例成员'Int'不能用于类型'Comment'”

在此处输入图片说明

I have found this answer that suggest to use the keyword static . 我已经找到了建议使用关键字static的 答案 However, as the point of the function that I am writing is to access the primary key after that the object has been created, having a static variable would not work. 但是,由于我要编写的函数的重点是在创建对象之后访问主键,因此具有静态变量将不起作用。

Any suggestion on how to improve this? 关于如何改善这一点的任何建议?

import Foundation
import RealmSwift

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

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

Quoting "@Octaviano Putra" in the comments this worked for me: 在对我有用的评论中引用“ @Octaviano Putra”:

primaryKey function should return the variable name of primary key variable, not the value, so u should return "id" instead Ref: realm.io/docs/swift/latest/#primary-keys primaryKey函数应该返回主键变量的变量名,而不是值,因此您应该返回“ id”,而不是Ref: realm.io/docs/swift/latest/#primary-keys

Type methods cannot directly access instance properties 类型方法不能直接访问实例属性

I'll add this answer to explain the telling error message [ emphasis mine]: 我将添加此答案以说明错误信息[ 强调我的]:

"Realm Swift: instance member ' Int ' cannot be used on type ' Comment '" “ Realm Swift: 实例成员 ' Int '不能用于类型 ' Comment '”

A type method cannot access instance members of the type without having explicit access to an instance of the type itself (which it does not, in you example above). 在没有显式访问类型本身实例的情况下, 类型方法不能访问该类型的实例成员 (在上面的示例中,它不是)。

From the Language Guide - Methods : 语言指南-方法中

Type Methods 类型方法

Instance methods, as described above, are methods that are called on an instance of a particular type . 如上所述,实例方法是在特定类型的实例上调用的方法。 You can also define methods that are called on the type itself . 您还可以定义在类型本身上调用的方法。 These kinds of methods are called type methods. 这些方法称为类型方法。 You indicate type methods by writing the static keyword before the method's func keyword. 您可以通过在方法的func关键字之前写入static关键字来指示类型方法。 Classes may also use the class keyword to allow subclasses to override the superclass's implementation of that method. 类也可以使用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"
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM