【问题标题】:Realm - Adding children to a parent, then querying results on parent领域 - 将子级添加到父级,然后在父级上查询结果
【发布时间】:2017-01-09 12:06:02
【问题描述】:

我正在研究如何将子级添加到 Realm (Swift) 父级,我想查询结果。

但是,我想出了一个崩溃

do {
   let realm = try Realm()
   try realm.write {

       for locomotive in locomotives
       {
           realm.add(locomotive, update: true)
       }


       let locomotives = realm.objects(Locomotive.self)
       for locomotive in locomotives {
           print (locomotive.name)
           for _ in stride(from: 0, to: locomotive.qty, by: 1) {
               let engine : Engine = Engine.init()
               locomotive.engines.append(engine)
           }
       }

   }
} catch let error as NSError {
   //TODO: Handle error
   print(error.localizedDescription as Any)
}

我要创建一定数量的孩子,添加到关系中

然后当我尝试查询它时;

    let locomotives = realm.objects(Locomotive.self)

    print(locomotives.count)

// Find all children that are linked to this specific parent
    for loco in locomotives {
        let engines = realm.objects(Engine.self).filter("parent == \(loco)")

        print("listing engines")
        for engine in engines {
            print ("engine: \(engine.parent)")
        }
    }

我的父类是(最基本的减去任何映射代码)

class Locomotive: Object, Mappable {
    dynamic var engineid: String = ""
   var engines = List<Engine>()
}

我的子类是:(最基本的减去任何映射代码)

class Engine: Object {
    let parent = LinkingObjects(fromType: Locomotive.self, property: "engines")
}

这会导致崩溃:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "parent == Locomotive {

我想获取给定孩子的所有父母姓名的列表;通常我会这样做:

for each child in parent.array
{
print child.parent.name
}

但在领域中,我无法访问父母的姓名。

如何查询父子关系以及与上述类似的命令(获取父级的名称属性)?

非常感谢

【问题讨论】:

    标签: swift realm parent-child


    【解决方案1】:

    领域LinkingObjects 对象不代表单个对象;它们代表一个可能包含多个对象的数组。因此,有必要查询您的对象是否存在于该数组中,而不是查询是否相等。

    let engines = realm.objects(Engine.self).filter("%@ IN parent", loco)
    

    此外,由于 Realm 查询符合 NSPredicate,因此有必要使用老式的 %@ 表示法,而不是 Swift 的内联代码语法。

    【讨论】:

      猜你喜欢
      • 2020-03-21
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 1970-01-01
      • 2021-06-23
      • 2015-08-14
      • 2020-09-17
      相关资源
      最近更新 更多