Why does Realm throw an exception when asking for `size == 4`?
My subclasses RLMObject
look like this:
@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
I want to filter an array PhotoRealm
differentSizeImages
to get a specific one ImageRealm
. I've tried using the following code:
PhotoRealm *photo = self.array[indexPath.row];
NSString *filter = @"size == 4";
ImageRealm *pecificImage = [[photo.differentSizeImages objectsWhere:filter] firstObject];
Here it is self.array
initialized like this:
self.array = [PhotoRealm allObjects];
The code throws an exception:
2017-03-24 03: 33: 36.891 project_name [46277: 3636358] *** Application terminated due to uncaught exception "Invalid predicate expressions", reason: "Predictive expressions must compare a key path and another key path or a constant value
Update:
Before I added the property size
, I was able to do the following (since I only had one image size):
ImageRealm *image = [photo.differentSizeImages objectAtIndex:0];
But now that I have added the property size
, I need to filter the array to select the correct image size.
See the following images to represent the data in my Realm file:
[
And I noticed examples of requests in the official Realm 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];
They look the same as what I am doing, so why am I seeing an exception?
source to share
When trying to use a predicate format string, size == 4
you see the same exception:
Application terminated due to uncaught exception "Invalid predicate expressions", reason: "Predicative expressions must compare a key path and another key reference or constant value"
The reason for this is that it size
is a reserved word in the format syntaxNSPredicate
. You can avoid the reserved words by prefixing them with a character #
, so your query becomes#size == 4
source to share