【问题标题】:RealmDB does not get populatedRealmDB 没有被填充
【发布时间】:2018-05-23 07:25:56
【问题描述】:

Realm 新手...希望能有一个简单的解决方法!

我有一个数据对象:

class GasFile : Object {
  @objc dynamic var gasFilename : String = ""
 // @objc dynamic var gasCategory : String? = ""
}

在我的ViewController 我有以下功能:

func PopulateRealmWithFilenames() {
    let fm = FileManager.default
    var path = Bundle.main.resourcePath!
    path += "/NBTFiles"
    //let items = try! fm.contentsOfDirectory(atPath: path)
    let items : [String] = try! fm.subpathsOfDirectory(atPath: path)

    for item in items {
        do {
            print("item for realm is: \(item)")
            try self.realm.write {
                let newGasFile = GasFile()
                newGasFile.gasFilename.append(item)
                print("newGasFile written ok")
            }
        } catch {
            print("Error writing new item to Realm \(error)")
        }
    }
}

这可以设置 RealmDB,但永远不会被填充。
该函数的目的是保存存储在名为 NBTFiles 的文件夹中的文件的所有文件名(而不是路径)。
我得到了“打印出来的 newGasfile 写得好”,所以它进入了循环。
数据类型错误? (我知道我可以把它放到一个数组中,但我想使用领域)

【问题讨论】:

  • 你读过docs吗?

标签: swift realm


【解决方案1】:

你想如何在不使用添加功能的情况下将新对象添加到领域? 你应该使用realm.add(object: newGasFile)

试试这个

func PopulateRealmWithFilenames() {
let fm = FileManager.default
var path = Bundle.main.resourcePath!
path += "/NBTFiles"
//let items = try! fm.contentsOfDirectory(atPath: path)
let items : [String] = try! fm.subpathsOfDirectory(atPath: path)

for item in items {


    do {
        print("item for realm is: \(item)")
        try self.realm.write {
            let newGasFile = GasFile()
            newGasFile.gasFilename.append(item)
            realm.add(object: newGasFile)
            print("newGasFile written ok")
        }
    } catch {
        print("Error writing new item to Realm \(error)")
    }
}
}

【讨论】:

  • 天啊!多么尴尬!谢谢 - 不敢相信我错过了 .add - 我是个白痴!谢谢大师!
猜你喜欢
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-07
  • 2014-06-18
  • 1970-01-01
  • 2023-03-29
  • 2011-11-15
相关资源
最近更新 更多