使用多级属性在RealmSwift中创建LinkingObjects属性

时间:2016-05-11 16:41:21

标签: swift realm realm-cocoa

根据Realm documentation for v0.102.0,这是你创建反向关系的方式:

class Person: Object {
    // ... other property declarations
    let dogs = List<Dog>()
}

狗(v1)

class Dog: Object {
    // ... other property declarations
    let owners = LinkingObjects(fromType: Person.self, property: "dogs")
}

假设我们有另一个名为DogFood的类,我们想要创建一个名为buyers的反向关系,它跟踪Person哪个Dog个实例吃DogFood那个class Dog: Object { // ... other property declarations let favoriteFoods = List<DogFood> let owners = LinkingObjects(fromType: Person.self, property: "dogs") } 的实例。我们可以尝试以下方法:

狗(v2)

class DogFood: Object {
    // ... other property declarations
    let buyers = LinkingObjects(fromType: Person.self, property: "dogs.favoriteFoods")
}

DOGFOOD

Property 'dogs.favoriteFoods' declared as origin of linking objects property 'buyers' does not exist.

但是,这会引发以下错误:class AsynchronousServiceTask extends AbstractBpmnActivityBehavior { val exec_id : String = "executionId" override def execute(execution : ActivityExecution) = { val future = Future { println("Something") } future onComplete { case _ => myobject.callSignalForMe(execution.getId) } } override def signal(execution : ActivityExecution, signalName : String, signalData : AnyRef) = { println("Signal called, leaving current activity..") leave(execution) } }

还有另一种方法可以达到同样的效果吗?

1 个答案:

答案 0 :(得分:1)

这可以通过过滤器来实现,但需要注意的是我们需要查询的DogFood对象需要成为Realm的一部分。

代码如下:

class DogFood: Object {
    // ... other property declarations
    var items: Results<Person> {
        if let realm = self.realm {
            return realm.objects(Person).filter(NSPredicate(format: "ANY dogs.favoriteFoods.id == %@", self.id))
        } else {
            return RealmSwift.List<Person>().filter("1 != 1")
        }
    }
}

属性realm的类型为Realm?,并通过Object的继承进入图片。它指向特定Object实例所在的领域,如果未分配给nil,则返回items。如果是这种情况,我们会强制属性Results<Person>返回一组空sl_storage = object_storage.get_client( username = environment['slos_username'], password = environment['api_key'], auth_url = environment['auth_url'] ) # get container sl_container = sl_storage[environment['object_container']] # get list, the search function doesn't actually work... containers = sl_container.search("icm10restapi-qa.zip.*")