直接使用领域对象(即作为 CollectionView 数据源)

Use Realm Object Directly (i.e as CollectionView Data Source)

所以我有这个领域对象 class :

import Realm
import RealmSwift

class Realm_item: Object {
    var item_ID : String!
 required init() {
            super.init()
        }

        // And this one too
        required override init(realm: RLMRealm, schema: RLMObjectSchema) {
            super.init(realm: realm, schema: schema)
        }

        // Now go nuts creating your own constructor
        init(myCustomValue: String) {
            self.item_ID = myCustomValue
            super.init()
        }


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

}

比我试图初始化它,但它只是卡住了,无一例外或 error/crash。

  let item = Realm_item(myCustomValue: "SampleString")


  self.dataSource.append(item)

我对你的代码的评论很少。

  • item_ID 应该是动态的
  • 最好为 item_ID 定义一个默认值,而不是让它成为可选值
  • 您不应该创建或覆盖 init,而只是为了方便而创建自定义 init
  • import Realm不需要import RealmSwift就够了

代码应如下所示。

import RealmSwift

class Realm_item: Object {
    dynamic var item_ID : String = ""

        // You should only define init(s) as convenience and call self.init() inside it.
      convenience init(myCustomValue: String) {
            self.init()
            self.item_ID = myCustomValue   
        }

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

然后你就按你的方式使用它。

 let item = Realm_item(myCustomValue: "SampleString")
  self.dataSource.append(item)

希望对您有所帮助。谢谢。

更新

  • 动态关键字是什么意思??请看这个Answer

  • 为什么我们要使用realm的动态变量?正如在 Realm 中提到的 Swift 文档

    Realm model properties need the dynamic var attribute in order for these properties to become accessors for the underlying database data.

    There are two exceptions to this: List and RealmOptional properties cannot be declared as dynamic because generic properties cannot be represented in the Objective-C runtime, which is used for dynamic dispatch of dynamic properties, and should always be declared with let.

  • 使用 Realm 对象作为 DataSource 是个好习惯吗?方式 您在代码示例中使用的数据源为 Array<Realm_Item> 是一个好方法,因为数组大小不会改变 自动而对象将自动更新(如果 代码的其他部分正在修改它)