我的 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
的 differentSizeImages
数组以检索特定的 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 文件中的数据:
[
而且,我注意到示例查询 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/