2017-01-06 71 views
2

我正在研究如何將子項添加到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 
} 

但在領域,我無法訪問父母的名稱。

如何查詢父 - 子關係以及類似的命令(獲取父母的名稱屬性)?

非常感謝

回答

2

境界LinkingObjects對象並不代表單個對象;它們表示可能有多個對象的數組。因此,有必要查詢您的對象是否存在於該數組中,而不是查詢是否相等。

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

此外,由於境界查詢符合NSPredicate,有必要用老派%@符號,而不是斯威夫特的內嵌代碼的語法。