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

标签 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

我想过滤 PhotoRealmdifferentSizeImages 数组以检索特定的 ImageRealm。我尝试使用以下代码:

PhotoRealm *photo = self.array[indexPath.row];
NSString *filter = @"size == 4";
ImageRealm *pecificImage = [[photo.differentSizeImages objectsWhere:filter] firstObject];

self.array 是这样初始化的:

self.array = [PhotoRealm allObjects];

代码抛出异常:

2017-03-24 03:33:36.891 project_name[46277:3636358] *** Terminating app due to uncaught exception 'Invalid predicate expressions', reason: 'Predicate expressions must compare a keypath and another keypath or a constant value'


更新: 在添加 size 属性之前,我可以执行以下操作(因为我只有一种图像尺寸):

ImageRealm *image = [photo.differentSizeImages objectAtIndex:0];

但现在我已经添加了 size 属性,我需要过滤数组以选择正确尺寸的图像。

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

Photo

[ differentSizeImgae[2]


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

// Query using a predicate string
RLMResults<Dog *> *tanDogs = [Dog objectsWhere:@"color = 'tan' AND name BEGINSWITH 'B'"];

// Query using an NSPredicate
NSPredicate *pred = [NSPredicate predicateWithFormat:@"color = %@ AND name BEGINSWITH %@",
                                                     @"tan", @"B"];
tanDogs = [Dog objectsWithPredicate:pred];

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

最佳答案

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

Terminating app due to uncaught exception 'Invalid predicate expressions', reason: 'Predicate expressions must compare a keypath and another keypath or a constant value'

原因是size is a reserved word in NSPredicate's format syntax .您可以通过在保留字前加上 # 字符来转义保留字,这样您的查询就会变成 #size == 4

关于ios - 为什么 Realm 在查询 `size == 4` 时抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42985668/

相关文章:

c# - Nhibernate 和枚举

swift - Swift 关系中的 Realm 不添加行

swift - Realm Swift 主键无法检索到正确的值

ios - 当数据库发生变化时,使用 Realm Swift 将数据推送到所有设备

ios - 在 swift IOS 中停止改变宽度的标签中的文本

ios - 为什么我的 sqlite 数据库在对核心数据模型进行版本控制时没有迁移?

ios - 如何在 objective-c 中识别模型、 View 和 Controller ?

ios - 从 Documents 目录存储和读取文件 iOS 5

database - 如何在 Android Studio 3.1 中查看数据库表

javascript - 为什么我的 mongodb 调用这么慢?