ios - 检查对象是否在另一个对象的 RLMArray 属性中

标签 ios objective-c realm

我正在寻找一些有效(或至少不那么复杂)的方法来确定 and Object 是否包含在另一个对象的 RLMArray 属性中。

如果您查看 Realm 文档,就会发现关于 Inverse relationships 的信息,无论如何,我不确定这种模式是否符合我正在寻找的行为。假设我们有一个 Person 和一个 Party 类。 Party 类有一个 guests 属性:

// Party.h
@interface Party : RLMObject
// ... other property declarations
@property NSString *partyID;
@property RLMArray<Person *><Person> *guests;
@end

在 RLMRealm 中,我们有一个“宇宙”的人,无论他们是否会协助任何一方。因此,一个人可能在几个聚会的客人列表中。当我打开一个派对时,我想展示一个包含“宇宙”中所有人的列表。而且我们应该能够注意到他们是否已经被邀请。

+---------+---------+
| Invited | Name    |
+---------+---------+
| NO      | Orlando |
| YES     | Kim     |
| NO      | Jorge   |
| NO      | JJ      |
| YES     | Axel    |
+---------+---------+

如果我使用反向关系,那么我必须创建一个包含 Person 中的关系的属性

// Person.h
@interface Person : RLMObject
// ...
@property (readonly) RLMLinkingObjects *assistingTo;
// ...
@end

因此对于显示人员列表的迭代,我将手动检查此人是否被邀请参加聚会

RLMResults *allPeople = [People allObjects];
Party *thisParty = [Party firstObject];

for (Person *p in allPeople) {
    if ([p.assistingTo indexOfObject:thisParty] > -1) {
        // Show the YES in the table
    } else {
        // Then the person is not attending the party
    }
}

我的工作方式是否正确?还有其他方法吗?

最佳答案

是的!你走在正确的轨道上! RLMLinkingObjectsNSPredicate 查询一起使用,因此获取参加特定聚会的所有人的列表非常简单,如下所示:

RLMResults *allPeopleAtTheParty = [Person objectsWhere:@"%@ IN assistingTo", thisParty]; 

这将返回一个 Person 对象的列表,这些对象在其 assistingTo 数组属性中具有特定的 thisParty 对象。

如果您想显示每个 Person 的表格,然后显示“参加/不参加”标签,那么它会变得有点棘手。您显然需要加载所有 Person 对象的正确列表,然后将其与过滤后的列表进行比较,以确定哪些人被邀请了,哪些人没有被邀请。

在构建 UITableViewCell 时,这可能的操作过于繁重,无法即时执行,所以我选择这样做:

1) 在 Person 上创建一个被忽略的属性来跟踪他们是否被邀请:

@interface Person : RLMObject
@property (nonatomic, assign) BOOL invited;
@end

@implementation Person
+ (NSArray *)ignoredProperties
{
   return @[@"invited"];
}
@end

2) 查询主列表和排序列表:

RLMResults *allPeople = [Person allObjects];
RLMResults *partyPeople = [Person objectsWhere:@"%@ IN assistingTo", thisParty]; 

3) 遍历 partyPeople 列表中的每个人,并在 allPeople 列表中的等效条目中更新 invited 属性:

for (Person *person in partyPeople) {
   NSInteger personIndex = [allPeople indexOfObject:person];
   if (personIndex == NSNotFound) {
      continue;
   }

   allPeople[personIndex].invited = YES;
}
  1. 设置 UITableView,使用 allPeople 作为其数据源。

如果您有任何问题,请告诉我!

关于ios - 检查对象是否在另一个对象的 RLMArray 属性中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38645366/

相关文章:

iphone - 如何从我的应用程序包中读取文本文件并将其显示在 UITextView 中

objective-c - 为属性创建我自己的 setter 时无限递归

ios - Realm 不能为零

ios - 如何从多个 Realm 模型创建一个 tableview?

ios - 如何平滑绘制图像的边缘?

ios - React Native iOS 卡在 LaunchScreen 上

ios - Swift iOS - 从 UIView 外部检测触摸拖动进入 UIView

ios - 如何从底部绘制View Controller

ios - 如何删除UIImageView的最后一张图片?

ios - 新用户进入 Realm 模式