ilt*_*giz 6 objective-c relationship realm ios
让我们说我有一个Dog和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)
Run Code Online (Sandbox Code Playgroud)
这是Realm示例项目的示例代码.唯一的区别是Dog实体有一个Person对象数组,owners换句话说就是与Persons 的反向关系dogs.
现在,我想要完成的事情是查询Dog具有Person其中一个的对象owners.
我怎样才能做到这一点?
Tho*_*yne 11
您只需要做[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]]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3737 次 |
| 最近记录: |