如何获得对象是它们的属性的所有对象?

时间:2018-12-08 05:04:53

标签: swift realm

class House: Object {
   @objc dynamic var address: Address?
}

class Shop: Object {
   @objc dynamic var address: Address?
}

class Address: Object {}

如果我有一个地址对象,如何获取与其关联的所有对象(商店和房屋),或者至少获取对象计数。

1 个答案:

答案 0 :(得分:0)

让我们使用直接方法举一个具体的例子:

假设您有问题中概述的三个对象

class Address: Object {
    @objc dynamic var street: String?
}

class House: Object {
    @objc dynamic var address: Address?
}

class Shop: Object {
    @objc dynamic var address: Address?
}

现在创建一些对象并存储在Realm中。定义两个地址a0,a1和三个房屋h0,h1,h2,确保房屋0和2的地址为a0。并且让我们也创建一个商店(s0),并为其指定地址0。

let a0 = Address()
a0.street = "123 Here Road"

let a1 = Address()
a1.street = "456 There Road"

let h0 = House()
h0.address = a0

let h1 = House()
h1.address = a1

let h2 = House()
h2.address = a0

let s0 = Shop()
s0.address = a0
and write it to realm

try! realm.write {
    realm.add(h0)
    realm.add(h1)
    realm.add(h2)
    realm.add(s0)
}

假设我们要获取对象的地址以123开头,然后获取与该地址关联的房屋和商店的数量。为了简洁起见,我没有提供任何真正的错误检查

let addressResults = realm.objects(Address.self).filter("street BEGINSWITH[cd] '123'")
let myAddressObject = addressResults.first!

let houseResults = realm.objects(House.self).filter("address == %@", myAddressObject)
print("house count: \(houseResults.count)")

let shopResults = realm.objects(Shop.self).filter("address == %@", myAddressObject)
print("shop count: \(shopResults.count)")

和结果

house count: 2
shop count: 1

作为替代解决方案,您可以定义地址,房屋和商店之间的关系。保持房屋和商店对象不变,像这样更改地址对象

class Address: Object {
    @objc dynamic var street: String?

    let houses = List<House>()
    let shops = List<Shop>()
}

然后创建一些对象并写入领域。

let h0 = House()
let h1 = House()
let h2 = House()

let s0 = Shop()

let a0 = Address()
a0.street = "123 Here Road"
a0.houses.append(h0)
a0.houses.append(h1)
a0.shops.append(s0)

let a1 = Address()
a1.street = "456 There Road"
a1.houses.append(h2)

然后获取每个地址的房屋和商店数量:

let addressResults = realm.objects(Address.self)

for address in addressResults {
    let street = address.street!
    let houseCount = address.houses.count
    let shopCount = address.shops.count
    print("street: \(street) has \(houseCount) houses and \(shopCount) shops")
}

和输出

street: 123 Here Road has 2 houses and 1 shops
street: 456 There Road has 1 houses and 0 shops