为什么Realm在查询`size == 4`时会抛出异常?

时间:2017-03-23 19:47:41

标签: ios database realm

我的RLMObject的子类看起来像这样:

@interface ImageRealm : RLMObject

@property NSString *httpsURL;
@property NSNumber<RLMInt> *size;

@end

RLM_ARRAY_TYPE(ImageRealm)

@interface PhotoRealm : RLMObject

@property NSNumber<RLMInt> *photoID;
@property RLMArray<ImageRealm *><ImageRealm> *differentSizeImages;  

- (id)initWithMantleModel:(PhotoModel *)photoModel;

@end

我想过滤PhotoRealm的{​​{1}}数组以检索特定的differentSizeImages。我尝试使用以下代码:

ImageRealm

PhotoRealm *photo = self.array[indexPath.row]; NSString *filter = @"size == 4"; ImageRealm *pecificImage = [[photo.differentSizeImages objectsWhere:filter] firstObject]; 的初始化位置如下:

self.array

代码抛出异常:

  

2017-03-24 03:33:36.891 project_name [46277:3636358] ***由于未捕获的异常终止应用程序&#39;无效的谓词表达式&#39;,原因:&#39;谓词表达式必须比较a keypath和另一个keypath或一个常量值&#39;

更新 在我添加self.array = [PhotoRealm allObjects]; 属性之前,我能够执行以下操作(因为我只有一个图像大小):

size

但是现在我已经添加了ImageRealm *image = [photo.differentSizeImages objectAtIndex:0]; 属性,我需要过滤数组以选择正确尺寸的图像。

请参阅以下图片,了解我的Realm文件中的数据:

Photo

[differentSizeImgae[2]

并且,我注意到示例查询in Realm's official documentation

size

这些看起来和我正在做的一样,为什么我会看到异常呢?

1 个答案:

答案 0 :(得分:12)

尝试使用谓词格式字符串size == 4时,您会看到如此异常:

  

由于未捕获的异常终止应用&#39;无效的谓词表达式&#39;,原因:&#39;谓词表达式必须比较键路径和另一个键路径或常量值&#39;

原因是size is a reserved word in NSPredicate's format syntax。您可以使用#字符作为前缀加上保留字,因此您的查询将成为#size == 4