Realm Cocoa: finding multiple objects by PKs

谁说我不能喝 提交于 2019-12-04 09:36:12

your first two options should work no problem. The simplest way to write this query is:

NSArray *primaryKeys = @[@"bar1", @"bar2", @"bar3"]
RLMResults *results = [RLMFoo objectsWhere:@"id IN %@", primaryKeys];

A method called objectsWithPredicate works too. Can you share more of your code/stack trace when using your first few methods? I think there are issues happening elsewhere

With your help, I was able to find the reason for this behaviour. My real code was something closer to:

  NSArray *primaryKeys = @[ @"bar1", @"bar2", @"bar3" ];

  NSString *primaryKeyName = @"bar";
  RLMResults *results =
      [RLMFoo objectsInRealm:self.realm
               withPredicate:[NSPredicate predicateWithFormat:@"%@ IN %@",
                                                              primaryKeyName,
                                                              primaryKeys]];

Which was in a method and the PKs and the PK name were parameters to the method call. In theory this would allow my class to retrieve whatever objects with whatever PK name. Turns out my mistake is in assuming predicateWithFormat would, in this case, work in a similar way to stringWithFormat and properly replace the PK name as the first argument and take the PK array as the second one. However the solution turned out to be first assembling the format string, and then the predicate:

  RLMResults *results = [RLMFoo
      objectsInRealm:self.realm
       withPredicate:[NSPredicate
                         predicateWithFormat:
                             [NSString stringWithFormat:@"%@ IN %%@", primaryKeyName],
                             primaryKeys]];

Thanks Yoshyosh for your time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!