2017-01-06 8 views
2

私はレルム(スウィフト)親に子を追加する方法を研究しており、結果を照会したい。レルム - 親に子を追加して親の結果を照会

しかし、私はそれを照会しようとすると、その後の関係

に追加し、私は子供の一定数を作成したいクラッシュ

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) 
} 

を考え出しますよ。 (その最も基本的なマイナス任意のマッピングコードで)

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

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>() 
} 

私の子供のクラスがある(その最も基本的なマイナス任意のマッピングコードで)ですこれによりクラッシュが発生します。

*** 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 
} 

しかし、私は親の名前にアクセスできません。

私は親子関係についてクエリを作成することはできますが、同様のコマンド(親の名前属性を取得する)も可能ですか?

感謝

答えて

2

レルムLinkingObjectsオブジェクトが単一のオブジェクトを表すものではありません。それらは潜在的に複数のオブジェクトの配列を表します。したがって、等価性を照会するのではなく、その配列にオブジェクトが存在するかどうかを照会する必要があります。レルムクエリがNSPredicateに準拠しているため

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

はさらに、それは代わりにスウィフトのインラインコードの構文の、古い学校%@表記を使用する必要があります。

関連する問題