【问题标题】:Querying on relationship arrays in Realm在 Realm 中查询关系数组
【发布时间】:2014-08-11 11:00:48
【问题描述】:

假设我有一个 DogPerson 领域对象,例如

@interface Dog : RLMObject

@property NSString *name;
@property NSInteger age;

@property RLMArray<Person> *owners;

@end

@implementation Dog

@end

RLM_ARRAY_TYPE(Dog)

@interface Person : RLMObject

@property NSString *name;
@property RLMArray<Dog> *dogs;

@end

@implementation Person

@end

RLM_ARRAY_TYPE(Person)

这是来自 Realm 示例项目的示例代码。唯一的区别是Dog 实体有一个Person 对象数组作为owners,换句话说,与Persondogs 成反比关系。

现在我要完成的事情是查询具有Person 作为owners 之一的Dog 对象。

我该怎么做?

【问题讨论】:

    标签: ios objective-c relationship realm


    【解决方案1】:

    您只需要做[Dog objectsWhere:@"ANY owners = %@", person],其中person 是您要查询的所有者。

    一个完整的例子:

    @protocol Person;
    
    @interface Dog : RLMObject
    @property NSString *name;
    @property NSInteger age;
    
    @property RLMArray<Person> *owners;
    @end
    
    @implementation Dog
    @end
    
    RLM_ARRAY_TYPE(Dog)
    
    @interface Person : RLMObject
    @property NSString *name;
    @property RLMArray<Dog> *dogs;
    @end
    
    @implementation Person
    @end
    
    RLM_ARRAY_TYPE(Person)
    
    void test() {
        RLMRealm *realm = RLMRealm.defaultRealm;
    
        [realm beginWriteTransaction];
        Person *person = [Person createInRealm:realm withObject:@{@"name": @"Tim"}];
    
        Dog *dog = [Dog createInRealm:realm withObject:@{@"name": @"Rover", @"age": @5, @"owners": @[person]}];
        [Dog createInRealm:realm withObject:@{@"name": @"Rex", @"age": @10, @"owners": @[]}];
        [realm commitWriteTransaction];
    
        RLMArray *dogs = [Dog objectsWhere:@"ANY owners = %@", person];
        assert(dogs.count == 1);
        assert([dog isEqual:dogs[0]]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多